<?php

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

        $id_nota = $_POST['nota_edt'];
        $_SESSION['cveNota'] = $id_nota; 

        $nta = get_nota_tb($id_nota);
        /* $id_session = getSessionId($id, $id_nota);
        edtBitSession($id_session); */
        $fecha_actual = new DateTime("now", new DateTimeZone('America/Mexico_City') );
        
      }else{
        $bandera = 1;

        $nota = crear_nota();
        if($nota[0]["INSERTADO"] == 1){
          $nta = get_nota($nota);
          $id_nota = $nta[0]["ID"];
          $_SESSION['cveNota'] =$id_nota;
          
          /* 
          $id_session = bitSession($id, $id_nota); */
        }   
        /*   */
        
      }
      
    
      
    }
    else{
      echo "<script> 
            document.location.href='/aqua-restaurant/';
        </script>";
    }
?>
<?php 
if ($bandera == 1) {
 ?> 
<!-- NOTA NUEVA -->
<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-2 align-items-center">
              <i class="material-icons ms-auto text-dark cursor-pointer redondo-b" style="width: 80px; height:80px;" type="button" data-bs-toggle="modal" data-bs-placement="top" title="Guardar" data-bs-target="#modalGuardar" id="btn_guardar_nota"><img style="padding: 20%;" width="80" src="../assets/img/icons/iconos-04.png"></i>
            </div>
            <div class="col-2 mb-2">
              <!-- <i class="material-icons ms-auto text-dark cursor-pointer redondo-b" style="width: 70px; height:70px;" type="button" data-bs-toggle="modal" data-bs-placement="top" title="Guardar" data-bs-target="#modalGuardar" id="btn_guardar_nota"><img style="padding: 20%;" width="70" src="../assets/img/icons/iconos-04.png"></i> -->
            </div>
            <div class="col-4 d-flex justify-content-center align-items-center">
              <h2 class="mb-0 text-center" id="nom_mesero"><?php echo $nta[3]['NOMBRE'];?></h2>
            </div>
            <div class="col-4 d-flex justify-content-center align-items-center">
              <h2 class="mb-0 text-center" id="clave_nota"><?php echo $nta[1]["CLAVE"]?></h2>
              <input type="hidden" class="form-control form-control-gd" id="bandera" value="<?php echo $bandera?>">
              <input type="hidden" class="form-control form-control-gd" id="ban2" value="<?php echo $ban = 0?>">
              <input type="hidden" class="form-control form-control-gd" id="note_id" data-session="<?php // echo $id_session?>" value="<?php // echo $id_nota?>">
            </div>
            
            
           
          </div>
        </div>
      </div>
      
        <!-- <div class="row pt-1"> -->
        <div class="col-lg-8 col-md-12 mb-lg-0 pt-1">
           
            
        </div>
        <div class="col-lg-8 col-sm-12 mb-lg-0 pt-1">
            <div class="card py-2">
            
            <div class="row">
                <div class="col-sm-4">
                  <hr class="dark horizontal my-0">
                
                  <div class="card-footer p-1">

                    <label class="form-label label-gd">No. personas</label>                   
                    <div class="input-group input-group-outline-gd" >
                      <!-- -->
                      <input type="text" class="form-control form-control-gd" id="no_personas" placeholder="No. Personas">
                    </div>
                  </div>
                
                    
                </div>
                <div class="col-sm-8 ">
                    <div class="card-footer p-1">
                      <label class="form-label label-gd">Comensal</label>
                      <div class="input-group input-group-outline-gd">
                          <input type="text" class="form-control form-control-gd" id="comensal" placeholder="Comensal">
                      </div>
                    </div>
                        
                </div>
                <div class="col-sm-4 ">
                  <div class="card-footer p-1">
                    <label class="form-label label-gd">Mesa</label>
                    <div class="input-group input-group-outline-gd">
                      <!--  -->
                      <input type="text" class="form-control form-control-gd" id="no_mesa" placeholder="No. Mesa">
                    </div>
                  </div>
                    
                </div>
                <div class="col-sm-4  text-center">
                    <div class="card-footer p-1">
                      <label class="form-label label-gd">Hora ini</label>
                      <div class="input-group input-group-outline-gd">
                          
                          <input type="text" class="form-control form-control-gd" id="hora_ini" value="<?php echo $nta[2]["HORA_INI"]?>" disabled>
                      </div>
                    </div>
                    
                </div>
                <div class="col-sm-4 text-center ">
                    
                    <div class="card-footer p-1">
                      <label class="form-label label-gd">Hora Up</label>
                      <div class="input-group input-group-outline-gd">
                          <!--  -->
                          <input type="text" class="form-control form-control-gd" placeholder="Hora Up" id="hora_edt" disabled>
                      </div>
                    </div>
                </div>
                
            </div>
            </div>
        </div>
        <div class="col-lg-4 col-sm-12 mb-lg-0  pt-1">
            <div class="card py-3">
              <div class="table-responsive">
                  <table class="table">
                    <thead >
                      <tr>
                        <th class="align-middle " scope="col">
                          <h4 class="mb-1 text-dark text-center font-weight-bold-tablet">Subtotal: </h4>
                        </th>
                        <th class="align-middle " scope="col">
                          <h4 class="mb-1 text-dark text-center font-weight-bold-tablet">Desc: </h4>
                        </th>
                        <th class="align-middle " scope="col">
                          <h4 class="mb-1 text-dark text-center font-weight-bold-tablet">Total: </h4>
                        </th>
                        
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <th>
                          <div class="d-flex flex-column">
                          <h4 class="mb-1 text-dark font-weight-bold-tablet text-center" id="subtotal" data-val="0">$ 0.00</h4>
                          </div>
                        </th>
                        <th>
                          <div class="d-flex flex-column">
                          <h4 class="mb-1 text-dark font-weight-bold-tablet text-center" id="descuento" data-val="0">$ 0.00</h4>
                          </div>
                        </th>
                        <th>
                          <div class="d-flex flex-column">
                          <h4 class="mb-1 text-dark font-weight-bold-tablet text-center" id="total" data-val="0">$ 0.00</h4>
                          </div>
                        </th>
                      </tr>
                    </tbody>
                  </table>
                  
              </div>
                  
                  
              
                <!-- <div class="row">
                   
                    <div class="col-lg-6 col-sm-6 text-center">
                        <div class="d-flex flex-column">
                          <h4 class="mb-1 text-dark font-weight-bold-tablet">Subtotal: </h4>
                        </div>
                        <div class="d-flex flex-column">
                          <h4 class="mb-1 text-dark font-weight-bold-tablet">Descuento: </h4>
                        </div>
                        <div class="d-flex flex-column">
                          <h4 class="mb-1 text-dark font-weight-bold-tablet">Total: </h4>
                        </div>
                    </div>
                    <div class="col-lg-6 col-sm-6 text-center">
                        <div class="d-flex flex-column">
                        <h4 class="mb-1 text-dark font-weight-bold-tablet" id="subtotal" data-val="0.00">$ 0.00</h4>
                        </div>
                        <div class="d-flex flex-column">
                        <h4 class="mb-1 text-dark font-weight-bold-tablet"  id="descuento" data-val="0"> 0</h4>
                        </div>
                        <div class="d-flex flex-column">
                        <h4 class="mb-1 text-dark font-weight-bold-tablet" id="total" data-val="0.00">$ 0.00</h4>
                        </div>
                    </div>
                    
                </div> -->
            </div>
        </div>
        <div class="col-lg-12 col-sm-12 mb-lg-0 pt-1 ">
          <div class="card pt-1">
              <div class="card-body px-0">
                <div class="row mb-2">
                  <div class="col-lg-4 col-sm-4 d-flex justify-content-center mt-2">
                    <span class="badge badge-sm btn bg-gradient-warning btn-nota" id="btn_agregar">Agregar</span>
                  </div>
                  <div class="col-lg-4 col-sm-4 d-flex justify-content-center  mt-2">
                    <span class="badge badge-sm btn bg-gradient-danger btn-nota" id="btn_eliminar_renglon">Eliminar</span>
                  </div>
                  <div class="col-lg-4 col-sm-4 d-flex justify-content-center  mt-2">
                    <span class="badge badge-sm btn bg-gradient-secondary btn-nota" id="btn_editar">Editar</span>
                  </div>
                </div>
                
              </div>

            </div>
          </div>
        
        </div>
        
        
        
        <div class="col-sm-12 mt-2">
          <div class="card">
            <div class="card-body px-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: 640px; 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 id="productsTableRow" class="">
                      </tbody>
                    </table>
                </div>
            </div>
          </div>
        </div>
    </div>
  </div>


</div>
<?php 
}
?>


<?php 
if ($bandera == 2) {
  ?> 
<!-- EDITAR NOTA -->
<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-2 align-items-center">
              <i class="material-icons ms-auto text-dark cursor-pointer redondo-b" style="width: 80px; height:80px;" type="button" data-bs-toggle="modal" data-bs-placement="top" title="Guardar" data-bs-target="#modalGuardar" id="btn_guardar_nota"><img style="padding: 20%;" width="80" src="../assets/img/icons/iconos-04.png"></i>
            </div>
            <div class="col-2 mb-2">
              <!-- <i class="material-icons ms-auto text-dark cursor-pointer redondo-b" style="width: 70px; height:70px;" type="button" data-bs-toggle="modal" data-bs-placement="top" title="Guardar" data-bs-target="#modalGuardar" id="btn_guardar_nota"><img style="padding: 20%;" width="70" src="../assets/img/icons/iconos-04.png"></i> -->
            </div>
            <div class="col-4 d-flex justify-content-center align-items-center">
              <h2 class="mb-0 text-center" id="nom_mesero"><?php echo $nta[3]['NOMBRE'];?></h2>
            </div>
            <div class="col-4 d-flex justify-content-center align-items-center">
              <h2 class="mb-0 text-center" id="clave_nota"><?php echo $nta[1]["CLAVE"]?></h2>
              <input type="hidden" class="form-control form-control-gd" id="bandera" value="<?php echo $bandera?>">
              <input type="hidden" class="form-control form-control-gd" id="ban2" value="<?php echo $ban = 0?>">
              <input type="hidden" class="form-control form-control-gd" id="note_id" data-session="<?php // echo $id_session?>" value="<?php // echo $id_nota?>">
            </div>
            
            
           
          </div>
        </div>
      </div>
      
        <!-- <div class="row pt-1"> -->
        <div class="col-lg-8 col-md-12 mb-lg-0 pt-1">
            
            
        </div>
        <div class="col-lg-8 col-sm-12 mb-lg-0 pt-1">
            <div class="card py-2">
            
            <div class="row">
                <div class="col-sm-4">
                <hr class="dark horizontal my-0">
                
                  <div class="card-footer p-1">
                    <label class="form-label label-gd">No. personas</label>
                    <div class="input-group input-group-outline-gd" >
                      <!--  -->
                      <input type="text" class="form-control form-control-gd" id="no_personas" value="<?php echo $nta[11]["PERSONAS"]?>" placeholder="No. Personas"> 
                    </div>
                  </div>
                
                    
                </div>
                <div class="col-sm-8  ">
                    <div class="card-footer p-1">
                      <label class="form-label label-gd">Comensal</label>
                      <div class="input-group input-group-outline-gd">
                          <input type="text" class="form-control form-control-gd" id="comensal" value="<?php echo $nta[13]["COMENSAL"]?>" placeholder="Comensal">
                      </div>
                    </div>
                        
                </div>
                <div class="col-sm-4 ">
                  <div class="card-footer p-1">
                    <label class="form-label label-gd">Mesa</label>
                    <div class="input-group input-group-outline-gd">
                      <!--  -->
                      <input type="text" class="form-control form-control-gd" id="no_mesa" value="<?php echo $nta[10]["MESA"]?>" placeholder="No. Mesa">
                    </div>
                  </div>
                    
                </div>
                <div class="col-sm-4 text-center">
                    <div class="card-footer p-1">
                    <label class="form-label label-gd">Hora ini</label>
                    <div class="input-group input-group-outline-gd">
                        
                        <input type="text" class="form-control form-control-gd" id="hora_ini" value="<?php echo $nta[2]["HORA_INI"]?>" disabled>
                    </div>
                    </div>
                    
                </div>
                <div class="col-sm-4 text-center">
                    
                    <div class="card-footer p-1">
                    <label class="form-label label-gd">Hora Up</label>
                    <div class="input-group input-group-outline-gd">
                        <!--  -->
                        <input type="text" class="form-control form-control-gd" value="<?php echo $nta[4]["EDICION"]?>" placeholder="Hora Up" id="hora_edt"  disabled>
                    </div>
                    </div>
                </div>
                
            </div>
            </div>
        </div>
        <div class="col-lg-4 col-sm-12 mb-lg-0 pt-1">
            <div class="card py-3">
              <div class="table-responsive">
                <table class="table">
                  <thead >
                    <tr>
                      <th class="align-middle " scope="col">
                        <h4 class="mb-1 text-dark text-center font-weight-bold-tablet">Subtotal: </h4>
                      </th>
                      <th class="align-middle " scope="col">
                        <h4 class="mb-1 text-dark text-center font-weight-bold-tablet">Desc: </h4>
                      </th>
                      <th class="align-middle " scope="col">
                        <h4 class="mb-1 text-dark text-center font-weight-bold-tablet">Total: </h4>
                      </th>
                      
                    </tr>
                  </thead>
                  <tbody>
                    <tr>
                      <th>
                        <div class="d-flex flex-column">
                        <h4 class="mb-1 text-dark font-weight-bold-tablet text-center" id="subtotal" data-val="<?php echo $nta[7]["SUBTOTAL"]?>"><?php echo '$ ' . $nta[7]["SUBTOTAL"]?></h4>
                        </div>
                      </th>
                      <th>
                        <div class="d-flex flex-column">
                        <h4 class="mb-1 text-dark font-weight-bold-tablet text-center" id="descuento" data-val="<?php echo $nta[8]["DESCUENTO"]?>"><?php echo  $nta[8]["DESCUENTO"]?></h4>
                        </div>
                      </th>
                      <th>
                        <div class="d-flex flex-column">
                        <h4 class="mb-1 text-dark font-weight-bold-tablet text-center" id="total" data-val="<?php echo $nta[9]["TOTAL"]?>"><?php echo '$ ' . $nta[9]["TOTAL"]?></h4>
                        </div>
                      </th>
                    </tr>
                  </tbody>
                </table>
                
              </div>
                
                
            </div>
        </div>
        <div class="col-lg-12 col-sm-12 mb-lg-0 pt-1 ">
          <div class="card pt-1">
              <div class="card-body px-0">
                <div class="row mb-2">
                  <div class="col-lg-4 col-sm-4 d-flex justify-content-center mt-2">
                    <span class="badge badge-sm btn bg-gradient-warning btn-nota" id="btn_agregar">Agregar</span>
                  </div>
                  <div class="col-lg-4 col-sm-4 d-flex justify-content-center  mt-2">
                    <span class="badge badge-sm btn bg-gradient-danger btn-nota" id="btn_eliminar_renglon">Eliminar</span>
                  </div>
                  <div class="col-lg-4 col-sm-4 d-flex justify-content-center  mt-2">
                    <span class="badge badge-sm btn bg-gradient-secondary btn-nota" id="btn_editar">Editar</span>
                  </div>
                </div>
                
              </div>

            </div>
          </div>
        
        </div>
       
        
        <div class="col-sm-12 mt-2">
          <div class="card">
            <div class="card-body px-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>
  </div>


</div>
<?php 
}
  ?> 
<!-- Modal AGREGAR PRODUCTO -->
<div class="modal fade" id="modalProducto" tabindex="-1" aria-labelledby="modalProducto" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered-product">
    <div class="modal-content">
      <div class="modal-header" style="background-color: #fb8c00">
        <div class="row" >
            <div id="content" class="col-12">  
                <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 pt-1">
                    <span class="hours h2">Hora: </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>
        <h3> <span id=""><?php echo $nta[1]["CLAVE"]?></span></h3>
        <!-- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> -->
      </div>
      
      <div class="modal-body">
        <form action="" method="post" id="formulario_crear_producto">
          <div class="row">
            
            <div class="col-sm-12 col-lg-12 d-flex align-items-center">
              <div class="card-footer p-2 list-finder">
                <div class="sizet-modal input-group input-group-outline-gd">
                    <!-- <label class="form-label">Producto</label> -->
                    <input type="text" class="form-control" style="font-size: 2em !important; " id="Producto" autocomplete = "off" placeholder="Producto">
                    <input type="hidden" id="idProducts" name="idProducts">
                    <div id="listProduct" class="list-group list-hide">
                        <div class="list-items" ></div>
                    </div>
                </div>
              </div>
            </div>
            <div class="col-sm-6 col-lg-6 d-flex align-items-center">
              <div class="card-footer p-2">
                <div class="input-group input-group-outline-gd">
                    <!-- <label class="form-label">Precio</label> -->
                    <input type="text" class="form-control" style="font-size: 2em !important;" id="Precio" placeholder="Precio">
                </div>
              </div>
            </div>
            <div class="col-sm-6 col-lg-6 d-flex align-items-center">
              <div class="card-footer p-2">
                <div class="input-group input-group-outline-gd">
                    <!-- <label class="form-label">Cantidad</label> -->
                    <input type="number" class="form-control" style="font-size: 2em !important;" id="quantity" value="1" placeholder="Cantidad">
                </div>
              </div>
            </div>
            <div class="col-sm-12 col-lg-12 d-flex align-items-center">
              <div class="card-footer p-2">
                <div class="sizet-modal coment-space input-group input-group-outline-gd">
                    <!-- <label class="form-label">Comentario</label> -->
                    <!-- <input type="text" class="form-control" style="font-size: 30px !important;" id="Comentario" placeholder="Comentario"> -->
                     <textarea class="form-control" style="font-size: 2em !important;" id="Comentario" placeholder="Comentario" name="" id=""></textarea>
                </div>
              </div>
            </div>
            <table class="table">
                  <thead></thead>
                    <tbody>
                      <tr>
                        <td>
                          <div class="input-group input-group-outline mt-4" id="tiempo" >
                            <div class="form-check form-check-inline text-center">
                                <input class="form-check-input" style="width: 2.75em !important; height:  2.75em !important;" type="radio" name="inlineRadioOptions" id="inlineRadio_T1" value="T1" checked>
                                <label class="form-check-label" style="font-size: 2em !important;" for="inlineRadio1">T1</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" style="width: 2.75em !important; height:  2.75em !important;" type="radio" name="inlineRadioOptions" id="inlineRadio_T2" value="T2">
                                <label class="form-check-label" style="font-size: 2em !important;" for="inlineRadio1">T2</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" style="width: 2.75em !important; height:  2.75em !important;" type="radio" name="inlineRadioOptions" id="inlineRadio_T3" value="T3">
                                <label class="form-check-label" style="font-size: 2em !important;" for="inlineRadio1">T3</label>
                            </div>
                            <div class="form-check form-check-inline">
                                <input class="form-check-input" style="width:2.75em !important; height:  2.75em !important;" type="radio" name="inlineRadioOptions" id="inlineRadio_En" value="En">
                                <label class="form-check-label" style="font-size: 2em !important;" for="inlineRadio1">Entrada</label>
                            </div>
                            
                          </div>
                        </td>
                      </tr>
                    </tbody>
                </table>
          </form>
        </div>
        <div class="row">
          <div class="col-6 d-flex align-items-center">
            <div id="materias_primas_x_producto"></div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        
        <button type="button" class="btn btn-secondary" style="font-size: 1.6em" id="btn-cerrar" data-bs-dismiss="modal">Cerrar</button>
        <button type="button" class="btn btn-primary text-white" style="font-size: 1.6em" id="btn_agregar_renglon">Agregar</button>
        <button type="button" class="btn btn-primary text-white" style="font-size: 1.6em" id="btn_editar_renglon">Editar</button>
      </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: #fb8c00">
          <div class="col-12 d-flex align-items-center justify-content-center" id="logo-card">
              
          </div>
        
      </div>
      <div class="modal-body">
      
        <div class="row ">
          <div class="col-12 d-flex align-items-center justify-content-center">
            <h3 id="title-card-delete"></h3>
             
          </div>
          <div class="col-12 d-flex align-items-center justify-content-center">
            <h4 class="mb-0" id="content-card-delete"></h4> 
          </div>
        </div>
      </div>
      <div class="modal-footer align-items-center justify-content-center">
        <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button> -->
        <button type="button" class="btn btn-primary text-white h4" id="eli_renglon"></button>
      </div>
    </div>
  </div>
</div>

<!-- Modal Cancelado -->
<div class="modal fade" id="modalCanceled" tabindex="-1" aria-labelledby="modalCanceled" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header" style="background-color: #fb8c00>
          <div class="col-12 d-flex align-items-center justify-content-center">
              <img src="../assets/img/icons/ban.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>PRODUCTO CANCELADO</h3>
             
          </div>
          <div class="col-12 d-flex align-items-center justify-content-center">
            <h6 class="mb-0"></h6> 
          </div>
        </div>
      </div>
      <div class="modal-footer align-items-center justify-content-center">
        <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button> -->
        <!-- <button type="button" class="btn btn-primary text-white h4" id="eliminar_renglon">Eliminar</button> -->
      </div>
    </div>
  </div>
</div>

<!-- Modal Accion Cancelada-->
<div class="modal fade" id="modalCancel" tabindex="-1" aria-labelledby="modalCancel" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header" style="background-color: #fb8c00">
          <div class="col-12 d-flex align-items-center justify-content-center">
              <img src="../assets/img/icons/ban.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> EL PRODUCTO NO PUEDE SER CANCELADO</h3>
             
          </div>
          <div class="col-12 d-flex align-items-center justify-content-center">
            <h6 class="mb-0"></h6> 
          </div>
        </div>
      </div>
      <div class="modal-footer align-items-center justify-content-center">
        <!-- <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cerrar</button> -->
        <!-- <button type="button" class="btn btn-primary text-white h4" id="eliminar_renglon">Eliminar</button> -->
      </div>
    </div>
  </div>
</div>

<!-- Modal ELIMINADO -->
<div class="modal fade" id="modalDeleted" tabindex="-1" aria-labelledby="modalDeleted" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered">
    <div class="modal-content">
      
      <div class="modal-body">
        <div class="row">
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <img src="../assets/img/icons/close-circle.png" alt="" width="250px">
          </div>
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <h1>ELIMINADO</h1>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal SUCCESS -->
<div class="modal fade" id="modalSuccess" tabindex="-1" aria-labelledby="modalSuccess" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-body">
      
        <div class="row">
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <img src="../assets/img/icons/success.png" alt="" width="250px">
          </div>
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <h1>REALIZADO</h1>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<!-- Modal CARGANDO -->
<div class="modal fade" id="modalLoading" tabindex="-1" aria-labelledby="modalLoading" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered">
    <div class="modal-content">
      
      <div class="modal-body">
        <div class="row">
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <img src="../assets/img/icons/refresh-circle.png" alt="" width="250px">
          </div>
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <h1>Cargando datos...</h1>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Modal MESA OCUPADA -->
<div class="modal fade" id="modalMesaOcupada" tabindex="-1" aria-labelledby="modalMesaOcupada" aria-hidden="true">
  <div class="modal-dialog modal-sm-lg modal-dialog-centered">
    <div class="modal-content">
      
      <div class="modal-body">
        <div class="row">
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <img src="../assets/img/icons/mesaOcupada.png" alt="" width="250px">
          </div>
          <div class="col-12 mt-4 d-flex align-items-center justify-content-center">
              <h1>MESA OCUPADA</h1>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<div class="toast-container position-fixed bottom-0 end-0 p-2">
  <div id="liveToast" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
    <div class="toast-header">
      <img src="../assets/img/icons/alert-circle.png" class="rounded me-2" alt="" width="25px">
      <strong class="me-auto">Nota abierta en otra sesion</strong>
      <!-- <small>11 mins ago</small> -->
      <!-- <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button> -->
    </div>
    <div class="toast-body">
      La nota a la cual has accedido, esta abierta desde otra sesion. Por favor verifica que estes accediendo a la nota que deseas editar.
    </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>
  let read = 0;
  let save = 0;
  let products = [];

  $(document).ready(function () {
    getListProducts('');
    let ban = parseInt($('#bandera').val());  
      //*** TABLA */
      //getNoteProducts()
    // let note_id = $("#note_id").val();
    // validarSesionesNotaUsuario(note_id)
    $('#ProductsTable').DataTable({
        //order: [[8, 'Desc']],
        ordering: false,
        dom: 'Blfrtip',
        searching: false,  
        lengthChange: false,
        /* select: {
            style: 'single',
            info: 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'},
        ],
    });
    //**** BOTONES */

    $('#btn_agregar').on('click', function(){
      cleanTr();
      $('#btn_agregar_renglon').css('display','block'); //MODIFICADO
      $('#btn_editar_renglon').css('display','none'); //MODIFICADO

      $('#Producto').prop('disabled', false); //MODIFICADO
      $('#Precio').prop('disabled', false); //MODIFICADO

      cleanModal(); // agregado
      $('#modalProducto').modal("show");
    });
    $('#btn-cerrar').on('click', function(){
      $('#modalProducto').modal("toggle");
    });
    $('#btn_agregar_renglon').on('click', function(){
      let val = validarDatosProd();
      //console.log(val);
      if (val == 1) {
        addProductNote();
      }
      // $('#modalProducto').modal("toggle");
    });

    // ************* Buscar producto **********
    $('#Producto')
      .unbind('keyup')
      .on('keyup', function () {
          let text = $(this).val().toUpperCase();
          selProduct(text);
    });

    $('#btn_guardar_nota').on('click', guardarNota);

    
    /**  */
    $('#btn_editar').unbind('click').on('click', function(){
      let prd_id = $(this).attr('data-id');
      let total = $(this).attr('data-total');
      let cantidad = $($(`.row-selected`).find('td')[0]).text();
      let producto = $($(`.row-selected`).find('td')[1]).text();
      let comentario = $($(`.row-selected`).find('td')[2]).text();
      let tiempo = $($(`.row-selected`).find('td')[3]).text();
      let precio = $($(`.row-selected`).find('td')[4]).text();
      
      $('#modalProducto').modal("show");

      $('#Producto').val(producto);
      $('#Precio').val(precio);
      $('#quantity').val(cantidad);
      $('#Comentario').val(comentario);
      $('#inlineRadio_'+tiempo).prop('checked', true);

      $('#Producto').prop('disabled', true);
      $('#Precio').prop('disabled', true);

      $('#btn_editar_renglon').css('display','block'); 
      $('#btn_agregar_renglon').css('display','none'); 

      $('#btn_editar_renglon').attr('data-id',prd_id);

      
    })
    $('#btn_editar_renglon').unbind('click').on('click', function(){
        let prd_id = $(this).attr('data-id');
        let cantidad = $('#quantity').val();
        let precio = $('#Precio').val();
        let tiempo = $('input[type="radio"]:checked').val();
        let comentario = $('#Comentario').val();
        let precio_total = parseInt(cantidad) * parseFloat(precio);

        editarRow(prd_id, cantidad, tiempo, comentario, precio_total);
      })
    $('#btn_eliminar_renglon').unbind('click').on('click', function(){
      
      let band = 0;
      let prd_id = $(this).attr('data-id');
      let total = $(this).attr('data-total');
      let img;
      if ($(`#${prd_id}`).attr('data-new') == '1') {
        $('#logo-card').html('<img src="../assets/img/icons/alert-circle.png" alt="" width="250px">')
        $('#title-card-delete').text("ELIMINANDO PRODUCTO");
        $('#content-card-delete').text("Estas por eliminar el producto");
        $('#eli_renglon').text("eliminar");
        band = 1;

      }else if($(`#${prd_id}`).attr('data-new') == '0'){
        
        $('#logo-card').html('<img src="../assets/img/icons/ban.png" alt="" width="250px">')
        $('#title-card-delete').text("ELIMINANDO PRODUCTO");
        $('#content-card-delete').text("Estas por eliminar el producto");
        $('#eli_renglon').text("eliminar");
        band = 2;
      }
      
      $('#modalAlert').modal("show");

      $('#eli_renglon').unbind('click').on('click', function(){
        if ($(`#${prd_id}`).attr('data-new') == '1') {
          deleteRow(prd_id, band,total);
        } else {
          if ($(`.row-selected`).attr('data-new') == '0') {
            if ($('.row-selected').attr('data-status') == 0) {
              deleteRow(prd_id, band,total);
              
            }else{
              delete_row(prd_id, band,total);
            }
          }
        }
        
      })
      
    });

    $('#no_mesa').on("blur", function(){
      let no_mesa = $('#no_mesa').val();
      validarMesa(no_mesa);
    });
    // seleccionar un renglon
    $(document).on('click', '#ProductsTable tbody tr', function(){
      
      if ($(this).hasClass('row-selected')) {
        cleanTr();
      }else{
        let prd_id = $(this).attr('id');
        let prd_time = $(this).attr('data-tiempo');
        let prd_total = $(this).attr('data-total');
        cleanTr();
        $(this).addClass('row-selected');
        
        $('#btn_eliminar_renglon').attr('data-id',prd_id);
        $('#btn_eliminar_renglon').attr('data-tiempo',prd_time);
        $('#btn_eliminar_renglon').attr('data-total',prd_total);

        $('#btn_editar').attr('data-id',prd_id);
        $('#btn_editar').attr('data-tiempo',prd_time);
        $('#btn_editar').attr('data-total',prd_total);
      }

      
    });

    if (ban == 2) {
      getNoteProducts();
      
    }
  });
  
  function guardarNota() {
      $('#btn_guardar_nota').off('click'); // desactiva

      let val = validarDatosNota();
      $('#btn_guardar_nota').off('click');
      if (val == 0) {
        $('#modalLoading').modal('show');
        readColTable();
        saveAll()
        
        products = [];
        // saveNote();
      }else{
        console.log('Error en validacion, completar datos');
        habilitarBotonGuardar();
      }
      
  }

  /** 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);
      }
    });
  }
  function validarDatosNota(){
    let personas = $('#no_personas').val();
    let comensal = $('#comensal').val();
    let mesa = $('#no_mesa').val();

    let cnt= 0; 
    if (personas > 0){
      $('#no_personas').removeClass('input_error');
    }else{
      cnt+=1
      $('#no_personas').addClass('input_error');
    }

    return cnt;
  }
  /** VALIDAR DATOS DEL MODAL PARA AGREGAR NUEVOS PRODUCTOS A LA NOTA*/
  function validarDatosProd(){
    let cant = $('#quantity').val();
    let price = $('#Precio').val();
    let product = $('#idProducts').val();

    let cnt= 0; 

    if (cant >= 1) {
      $('#quantity').removeClass('input_error');
      cnt = 1;
    }else{
      $('#quantity').addClass('input_error');
      cnt = 0;
    }

    if (price >= 0) {
      $('#Precio').removeClass('input_error');
      cnt = 1;
    }else{
      $('#Precio').addClass('input_error');
      cnt = 0;
    }

    if (product > 0) {
      $('#Producto').removeClass('input_error');
      cnt = 1;
    }else{
      $('#Producto').addClass('input_error');
      cnt = 0;
    }
    return cnt;
  }
  /* ********************************* */
  

  function getListProducts(word) {
    // console.log(word);
    let pagina = "../functions/list_products.php"; 
    let datos = { word: word }; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = searchProduct;
    ajax_function(pagina, datos, dtipo, tipo, selector);
  }
  function searchProduct(dt){
    /* console.log(dt); */
    var sl = $('#Producto').offset();
    $('#listProduct .list-items').html('');
    $('#listProduct').css({top: sl.top + 60 + 'px'});// volver a tomar al hacer scroll.
    if (dt[0].id > 0) {
        $.each(dt, function (v, u) {
            let H = `<div class="list-item" id="${u.id}" data_complement="${u.pro_clave}|${u.id}|${u.pro_nombre.replace(/"/g, '')}" data-price="${u.pro_precio_venta}">${u.pro_nombre}</div>`;
            $('#listProduct .list-items').append(H);
        });
    }
    
    $('#txtProducts').on('focus', function () {
        $('#listProduct').slideDown('fast');
    });

    $('#txtProducts').on('scroll', function(){
        sl = $('#txtProducts').offset();
        $('#listProduct').css({top: sl.top + 60 + 'px'});
    });
    $('#listProduct').on('mouseleave', function () {
        $('#listProduct').slideUp('fast');
    });

    $('#listProduct .list-item').on('click', function () {
        let prdNm = $(this).html();
        let prdId = $(this).attr('id');
        let price = $(this).attr('data-price');
        $('#Producto').val(prdNm);
        $('#idProducts').val(prdId);
        $('#Precio').val(price);
        $('#listProduct').slideUp(100);
        
    });
  }
  function selProduct(res) {
  
    res = res.toUpperCase();
    if (res == '') {
        $('#listProduct').slideUp(100);
    } else {
        $('#listProduct').slideDown(400);
    }
    if (res.length > 1) {
        if (res.length == 2) {
            // getListProducts(res)
            $('#listProduct .list-items div.list-item').css({display: 'block'});
        } else {
            $('#listProduct .list-items div.list-item').css({display: 'none'});
            $('#listProduct .list-items div.list-item').each(function (index) {
                var cm = $(this).attr('data_complement').toUpperCase().replace(/|/g, '');
                
                cm = omitirAcentos(cm);
                var cr = cm.indexOf(res);
                if (cr > -1) {
                    $(this).css({display: 'block'});
                }
            });
        }
        // rowCurr.show();
    }else {
        var sl = $('#Producto').offset();
        $('#listProduct').css({top: sl.top + 60 + 'px'});// volver a tomar al hacer scroll.
        $('#listProduct .list-items div.list-item').css({display: 'none'});
    }
  }

  /** Omite acentos para su facil consulta */
  function omitirAcentos(text) {
      var acentos = 'ÃÀÁÄÂÈÉËÊÌÍÏÎÒÓÖÔÙÚÜÛãàáäâèéëêìíïîòóöôùúüûÑñÇç';
      var original = 'AAAAAEEEEIIIIOOOOUUUUaaaaaeeeeiiiioooouuuunncc';
      for (var i = 0; i < acentos.length; i++) {
          text = text.replace(acentos.charAt(i), original.charAt(i));
      }
      return text;
  }
  // ****************************************

  /* AGREGAR PRODUCTO A LA TABLA DE PRODUCTOS */
  function addProductNote(){
    let producto = $('#Producto').val();
    let precio = $('#Precio').val();
    let canti = $('#quantity').val();
    let comentario = $('#Comentario').val();
    let tiempo = $('input[type="radio"]:checked').val();
    let total = parseFloat(precio) * parseInt(canti);
    let tabla = $('#ProductsTable').DataTable();
    let id_prod = $('#idProducts').val();
    let cant = parseInt($('#ban2').val());
    let id = cant + 1;
    let comensal = $('#comensal').val();

    var rowNode = tabla.row
      .add({
        Nombre: `<div class="producto" id="pdn${id}"> ${producto}</div>` ,
        Comentarios: comentario,
        Cantidad: canti,
        Tiempo: tiempo,
        Precio: precio,
      })
    .draw().node();
    $complement = `${canti}|${comentario}|${comensal}|${tiempo}`
    
    $(rowNode).attr('id', id_prod).attr('data-tiempo', tiempo).attr('data-idProd', id).attr('data-new', 1).attr('data-complement', $complement);
    cleanModal();
    $('#ban2').val(id);
    editarTotales()

  }
  /** *************************************** */

  /* LIMPIAR  */
  function cleanModal(){
    $('#Producto').val('');
    $('#idProducts').val('');
    $('#Precio').val('');
    $('#quantity').val('1');
    $('#Comentario').val('');
    $('#inlineRadio_T1').prop('checked', true);
    $('#Producto').removeClass('input_error')
    $('#Precio').removeClass('input_error')
    $('#quantity').removeClass('input_error')
  }
  
  function cleanTr(){
    
    //$('#btn_eliminar_renglon').attr('id',0).attr('data-tiempo',0);
    $('.row-selected').each(function(index, element){
      $(element).removeClass('row-selected');
    })
  } 

  function editarTotales(){
    let subtotal = 0;
    let total_pagar=0;
    let descuento = parseFloat($('#descuento').attr('data-val'));

    $('#ProductsTable tbody tr').each(function (v, u){
      let qty = $($(u).find('td')[0]).text();
      let price = $($(u).find('td')[4]).text();
      let total = qty * price;
      subtotal = subtotal + total;
    })

    total_pagar = subtotal - (subtotal * (descuento/100)); 
    
    $('#subtotal').text('$ '+ parseFloat(subtotal).toFixed(2));
    $('#total').text('$ '+ parseFloat(total_pagar).toFixed(2));

    $('#subtotal').attr('data-val',subtotal)
    $('#total').attr('data-val',total_pagar)


  }
  /** editar */
  function editarRow(prd_id, cantidad, tiempo, comentario, precio){
    // console.log(prd_id, cantidad, tiempo, comentario, precio);
    $($(`.row-selected`).find('td')[0]).text(cantidad);
    $($(`.row-selected`).find('td')[2]).text(comentario);
    $($(`.row-selected`).find('td')[3]).text(tiempo);
    $(`.row-selected`).attr('data-tiempo',tiempo);
    editarTotales();
    cleanModal();
    $('#modalProducto').modal('toggle');
    //cleanTr();
  }
  /** ELIMINAR RENGLON*/
  function deleteRow(id, band,total_pag){
    
    let tabla = $('#ProductsTable').DataTable();
    let total;     
    let subtotal;  
    tabla
        .row($(`.row-selected`))
        .remove()
        .draw();
    $('#modalAlert').modal("toggle");
    editarTotales()

    total     = parseFloat($('#total').attr('data-val'));
    subtotal  = parseFloat($('#subtotal').attr('data-val'));

    if(band == 2){
      let pagina = '../functions/tablet/notas/cancelar_prod.php';
      let datos = { pdn_id: id, total: total, subtotal: subtotal};
      let dtipo = "JSON"; 
      let tipo = "POST"; 
      let selector = putCancelProduct;
      ajax_function(pagina, datos, dtipo, tipo, selector);
      
    }else{
      //$('#modalDeleted').modal('show')
    }
    
  }
  function delete_row(id, band,total_pag){
    
    let tabla = $('#ProductsTable').DataTable();
    let total;     
    let subtotal;  
    tabla
        .row($(`.row-selected`))
        .remove()
        .draw();
    $('#modalAlert').modal("toggle");
    editarTotales()

    total     = parseFloat($('#total').attr('data-val'));
    subtotal  = parseFloat($('#subtotal').attr('data-val'));

    if(band == 2){
      let pagina = '../functions/tablet/notas/eliminar_prod.php';
      let datos = { pdn_id: id, total: total, subtotal: subtotal};
      let dtipo = "JSON"; 
      let tipo = "POST"; 
      let selector = putCancelProduct;
      ajax_function(pagina, datos, dtipo, tipo, selector);
      
    }else{
      //$('#modalDeleted').modal('show')
    }
    
  }
  function putCancelProduct(dt){
    //console.log(dt);
    if (dt == 1) {
      // $('#modalCanceled').modal('show');
    }
   /*  $('#modalCanceled').modal('toggle') */
  }
  /**  */

  
  /** COLOCAR LOS PRODUCTOS DE UNA NOTA A EDITAR */
  function getNoteProducts(){
    let pagina = "../functions/tablet/notas/list_note_products.php"; 
    let datos = { id_nota: 0 }; 
    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;
    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();
        $complement = `${u.pdn_cantidad}|${u.pdn_comentario}|${u.pdn_comensal}|${u.pdn_tiempo}`
        $('#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).attr('data-complement',$complement).addClass(bg_color);
      });
    }
    
  }
  /** */


  /** GUARDAR NOTA */
  function readColTable() {
    
    let comensal = $('#comensal').val();
    $('#ProductsTable tbody tr').each(function (v, u){
      let qty = $($(u).find('td')[0]).text();
      let productName = $($(u).find('td')[1]).text();
      let coment = $($(u).find('td')[2]).text();
      let time = $($(u).find('td')[3]).text();
      let price = $($(u).find('td')[4]).text();

      let id_prod = $(this).attr('id');
      let dtnew = $(this).attr('data-new');
      let tiempo = $(this).attr('data-tiempo');
      let bandera = $("#bandera").val()

      let cantidad_ant = "";
      let comentario_ant ="";
      let comensal_ant = "";
      let tiempo_ant ="";

      if ($(this).attr('data-complement')) {
        cantidad_ant = $(this).attr('data-complement').split('|')[0];
        comentario_ant = $(this).attr('data-complement').split('|')[1];
        comensal_ant = $(this).attr('data-complement').split('|')[2];
        tiempo_ant = $(this).attr('data-complement').split('|')[3];
      }
      
      /* let datos;
      let pagina = "../functions/tablet/notas/save_prod_note.php"; 

      datos = {
          'prd_name': productName,
          'coment': coment,
          'comensal': comensal,
          'tiempo': tiempo,
          'price':price,
          'new': dtnew,
          'id_prd': id_prod,
          'cant': qty,
          'bandera': bandera,
          'comensal_ant': comensal_ant,
          'cantidad_ant': cantidad_ant,
          'tiempo_ant': tiempo_ant,
          'comentario_ant': comentario_ant,
        } */
      
      if (id_prod) {
        console.log(id_prod)
        // saveProductNote(datos, pagina);
        agregarProducto(productName, coment, comensal, tiempo, price, dtnew, id_prod, qty, bandera, comensal_ant, cantidad_ant, tiempo_ant, comentario_ant)
      }
      
    });
    console.log(products)
  }

  function saveProductNote(datos, pagina){
    let dtipo = "JSON"; 
    let tipo = "POST"; 
    let selector = putProductNote;
    ajax_function(pagina, datos, dtipo, tipo, selector);
  }

  function putProductNote(dt){
    if (dt >= 1) {
      read = 1;
    }
  }
/* 
  function saveNote(){
    let personas = $('#no_personas').val();
    let comensal = $('#comensal').val();
    let mesa = $('#no_mesa').val();
    let hora_ini = $('#hora_ini').val();
    let hora_fin = $('#hora_edt').val();
    let subtotal = $('#subtotal').attr('data-val');
    let descuento = $('#descuento').attr('data-val');
    let total = $('#total').attr('data-val');
    let note_id = $('#note_id').val();
    let bandera = $("#bandera").val()
    let datos;
    // let session_id = $('#note_id').attr('data-session');

    datos = {
      'note_id' : note_id,
      'personas' : personas,
      'comensal' : comensal,
      'mesa' : mesa,
      'hora_ini' : hora_ini,
      'hora_fin' : hora_fin,
      'subtotal' : subtotal,
      'descuento' : descuento,
      'total' : total,
      'bandera': bandera
      // 'session_id' : session_id,
    }
    
      let pagina = "../functions/tablet/notas/save_note.php"; 
      let dtipo = "JSON"; 
      let tipo = "POST"; 
      let selector = putNota;
      ajax_function(pagina, datos, dtipo, tipo, selector);
    
    
  }
  function putNota(dt){
    if(dt == 1){
      save = 1;
    }
    if (save == 1) {
      $('#modalLoading').modal('toggle');
      //$('#modalSuccess').modal('show');
      setTimeout(function() {
        location.href ="/aqua-restaurant/usuario_mesero/sale_notes.php";
      }, 500);
    }
  } */
  /** */

  /** VALIDAR MESA */
  function validarMesa(no_mesa){
    $.ajax({
            data: {no_mesa: no_mesa},
            url: '../functions/validar_mesa.php',
            type: 'post',
            success:  function (response) {
              if (response==0) {
                //modalMesaOcupada
                $('#modalMesaOcupada').modal('show'); 
              }
              //console.log(response);
            },
            error: function (error) {
                console.log(error); 
            }
        });
  }

  /** VALIDAR SESIONES DE NOTA */
  function validarSesionesNotaUsuario(ntv_id){
    $.ajax({
            data: {ntv_id: ntv_id},
            url: '../functions/sesion_nota_usuario.php',
            type: 'post',
            success:  function (response) {
              if (response==0) {
                //modalMesaOcupada
                $("#liveToast").show();
              }
              //console.log(response);
            },
            error: function (error) {
                console.log(error); 
            }
        });
  }
  function saveAll()
  {
    let pagina = "../functions/tablet/notas/save_note_v2.php"; 
    let dtipo = "JSON"; 
    let tipo = "POST"; 

    let personas = $('#no_personas').val();
    let comensal1 = $('#comensal').val();
    let mesa = $('#no_mesa').val();
    let hora_ini = $('#hora_ini').val();
    let hora_fin = $('#hora_edt').val();
    let subtotal = $('#subtotal').attr('data-val');
    let descuento = $('#descuento').attr('data-val');
    let total = $('#total').attr('data-val');
    let note_id = $('#note_id').val();
    let bandera1 = $("#bandera").val()

    const datos = {
        note_id : note_id,
        personas : personas,
        comensal : comensal1,
        mesa : mesa,
        hora_ini : hora_ini,
        hora_fin : hora_fin,
        subtotal : subtotal,
        descuento : descuento,
        total : total,
        bandera: bandera1,
        products: products
    };

    $.ajax({
    type: tipo,
    contentType: "application/json",
    data: JSON.stringify(datos),
    url: pagina,
    success: function (dt) {
      console.log(dt)
      if (dt == 1) {
        $('#modalLoading').modal('toggle');
        //$('#modalSuccess').modal('show');
        setTimeout(function() {
          location.href ="/aqua-restaurant/usuario_mesero/sale_notes.php";
        }, 500);
      }
      else{
        habilitarBotonGuardar()
      }
      }, error(e) {
        console.log(e);
        habilitarBotonGuardar()
      }
    });
  }
  function habilitarBotonGuardar() {
      $('#btn_guardar_nota').on('click', guardarNota); // vuelve a activar
  }

  /* */
  function agregarProducto(productName, coment, comensal, tiempo, price, dtnew, id_prod, qty, bandera, comensal_ant, cantidad_ant, tiempo_ant, comentario_ant){
    

    products.push({
        prd_name: productName,
        coment: coment,
        comensal: comensal,
        tiempo: tiempo,
        price:price,
        new: dtnew,
        id_prd: id_prod,
        cant: qty,
        bandera: bandera,
        comensal_ant: comensal_ant,
        cantidad_ant: cantidad_ant,
        tiempo_ant: tiempo_ant,
        comentario_ant: comentario_ant,
    });
  }

  
</script>
<!--@Footer-->
