<?php
require_once 'conexion.php';
$mesa_id = 1; // Cambiar este número al clonar
$productos_mesas = mysqli_fetch_all(
    mysqli_query($con, "SELECT id, nombre, precio, stock, es_cocina FROM productos_mesas WHERE visible = 1 ORDER BY nombre ASC"),
    MYSQLI_ASSOC
);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Mesa <?= $mesa_id ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
:root {
  --color-primary: #5e72e4;
  --color-secondary: #f7fafc;
  --color-success: #2dce89;
  --color-danger: #f5365c;
  --color-warning: #fb6340;
  --color-info: #11cdef;
  --color-dark: #212529;
  --color-light: #f8f9fa;
}

body {
background: linear-gradient(135deg, #2b2d42 0%, #4b6cb7 100%);
  font-family: 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif;
}

/* Card principal rediseñada */
.card-mesa {
  width: 320px;
  border: none;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  transition: all 0.3s ease;
  overflow: hidden;
  margin-bottom: 20px;
  background: white;
}

.card-mesa:hover {
  box-shadow: 0 8px 20px rgba(0,0,0,0.12);
  transform: translateY(-2px);
}

.card-header-mesa {
  background: var(--color-primary);
  color: white;
  padding: 12px 15px;
  border-bottom: none;
  position: relative;
}

.card-header-mesa h4 {
  margin: 0;
  font-size: 1.1rem;
  font-weight: 600;
}

.card-body-mesa {
  padding: 15px;
}

/* Campos de formulario compactos */
.form-control-smaller {
  padding: 6px 10px;
  font-size: 0.85rem;
  height: calc(1.5em + 0.75rem + 2px);
}

/* Lista de productos más compacta */
.lista-productos-mesa {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  max-height: 180px;
  overflow-y: auto;
  padding: 5px;
  margin: 10px 0;
}

.lista-productos-mesa li {
  width: 100%;
  font-size: 0.8rem;
  padding: 6px 8px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  background: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  transition: all 0.2s;
}

.lista-productos-mesa li:hover {
  background: #f8f9fa;
  border-color: #dee2e6;
}

/* Ticket más compacto */
.ticket-box {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 10px;
  margin-top: 10px;
  font-size: 0.85rem;
}

.ticket-box div {
  margin-bottom: 4px;
}

.ticket-box div:last-child {
  font-weight: 600;
  color: var(--color-success);
  margin-bottom: 0;
}

/* Controles de cantidad más pequeños */
.qty-controls .btn {
  padding: 2px 6px;
  font-size: 0.7rem;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.qty-controls .btn-del {
  width: auto;
  padding: 2px 8px;
}

.qty-controls .qty {
  min-width: 20px;
  text-align: center;
}

/* Dropdown más compacto */
.dropdown-container {
  position: relative;
}

.dropdown-list {
  z-index: 1050;
  max-height: 200px;
  overflow-y: auto;
  font-size: 0.85rem;
}

.dropdown-list li {
  cursor: pointer;
  padding: 6px 12px;
}

/* Bloque cocina compacto */
.bloque-cocina {
  font-size: 0.85rem;
  padding: 8px;
  margin-top: 8px;
}

/* Botones más compactos */
.btn-smaller {
  padding: 4px 8px;
  font-size: 0.8rem;
}

/* Input group más compacto */
.input-group-smaller .form-control,
.input-group-smaller .btn {
  height: calc(1.5em + 0.5rem + 2px);
  padding: 0.25rem 0.5rem;
  font-size: 0.85rem;
}

/* Scrollbar personalizada */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* Efectos hover para botones */
.btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(0,0,0,0.1);
}

/* Transiciones suaves */
.btn, .form-control, .lista-productos-mesa li {
  transition: all 0.2s ease;
}

/* Espaciado optimizado */
.mb-smaller {
  margin-bottom: 8px !important;
}

/* Iconos más pequeños */
.fa-sm {
  font-size: 0.8rem;
}

  .chat-icon{font-size:1rem;line-height:1;padding:2px 6px;}
</style>
</head>
<body class="p-3">
<script>const MESA_ID = <?= $mesa_id ?>;
let currentComandaId = localStorage.getItem('mesa_'+MESA_ID+'_comanda') || null;</script>

<div class="card-mesa">
  <div class="card-header-mesa d-flex justify-content-between align-items-center">
    <h4><i class="fas fa-utensils me-2"></i>Mesa <?= $mesa_id ?></h4>
    <button type="button" class="btn btn-light btn-sm chat-icon" onclick="abrirModalComentario(<?= $mesa_id ?>)" title="Comentarios">💬</button>
  </div>
  
  <div class="card-body-mesa">
    <form id="form_mesa_<?= $mesa_id ?>">
      <div class="mb-smaller">
        <label class="form-label small">Cliente</label>
        <input type="text" class="form-control form-control-smaller" name="cliente">
      </div>

      <div class="mb-smaller">
        <label class="form-label small">Hora</label>
        <input type="time" class="form-control form-control-smaller hora-mesa" name="hora" value="<?= date('H:i') ?>">
      </div>

      <div class="mb-smaller">
        <label class="form-label small">Productos</label>
        <div class="dropdown-container position-relative">
          <div class="input-group input-group-smaller">
            <input type="text" id="input_<?= $mesa_id ?>" class="form-control campo-buscar" placeholder="Buscar producto...">
            <button class="btn btn-outline-secondary" type="button" onclick="toggleDropdown(<?= $mesa_id ?>)">
              <i class="fas fa-caret-down fa-sm"></i>
            </button>
            <button class="btn btn-primary" type="button" onclick="agregarProductoInput(<?= $mesa_id ?>)">
              <i class="fas fa-plus fa-sm"></i>
            </button>
          </div>
          <ul class="list-group position-absolute w-100 d-none dropdown-list" id="dropdown_<?= $mesa_id ?>"></ul>
        </div>

        <ul class="list-group lista-productos-mesa mt-2" id="productos_mesa_<?= $mesa_id ?>"></ul>
        <div id="bloque_cocina_<?= $mesa_id ?>" class="bloque-cocina"></div>
      </div>

      <div class="ticket-box" id="ticket_mesa_<?= $mesa_id ?>">
        <div>Hora: <span class="ticket-hora"><?= date('H:i') ?></span></div>
        <div>Productos: -</div>
        <div>Total: $0.00</div>
      </div>

      <div class="mt-2 text-end">
        <button type="button" class="btn btn-success btn-smaller" onclick="abrirModalCobroMesa(<?= $mesa_id ?>)">
          <i class="fas fa-cash-register me-1"></i>Cobrar
        </button>
      </div>
    </form>
  </div>
</div>

<!-- Modal cobro mesa -->
<div class="modal fade" id="modalCobroMesa" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content"></div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>

<script>
// ---------- DATA ----------
const CAT = <?= json_encode($productos_mesas, JSON_UNESCAPED_UNICODE) ?>;
const LS_KEY = id => 'mesa_'+id+'_state';
const money = n => '$'+n.toFixed(2).replace('.',',');

// ---------- DROPDOWN ----------
function buildDropdown(id,term=''){
  const list=$('#dropdown_'+id).empty();
  const data=term?CAT.filter(p=>p.nombre.toLowerCase().includes(term.toLowerCase())):CAT;
  if(!data.length){list.addClass('d-none');return;}
  data.forEach(p=>{
    $('<li class="list-group-item list-group-item-action">'+p.nombre+'</li>').appendTo(list)
      .on('click',()=>{addProductoToMesa(id,p.id,p.nombre,parseFloat(p.precio),p.es_cocina);$('#input_'+id).val('');hideDropdown(id);});
  });
  list.removeClass('d-none');
}
function hideDropdown(id){$('#dropdown_'+id).addClass('d-none');}
function toggleDropdown(id){$('#dropdown_'+id).hasClass('d-none')?buildDropdown(id):hideDropdown(id);}
$(document).on('input','.campo-buscar',function(){const id=this.id.split('_').pop();buildDropdown(id,this.value.trim());});
$(document).on('keydown','.campo-buscar',function(e){if(e.key==='Enter'){e.preventDefault();const id=this.id.split('_').pop();agregarProductoInput(id);hideDropdown(id);}});
$(document).on('click',e=>{if(!$(e.target).closest('.dropdown-container').length) $('.dropdown-list').addClass('d-none');});

// ---------- PRODUCTOS ----------
function agregarProductoInput(id){
  const txt=$('#input_'+id).val().trim(); if(!txt) return;
  const prod=CAT.find(p=>p.nombre.toLowerCase()===txt.toLowerCase());
  const pid=prod?prod.id:'c_'+Date.now();
  const nom=prod?prod.nombre:txt;
  const pre=prod?parseFloat(prod.precio):0;
  const ec=prod?prod.es_cocina:0;
  addProductoToMesa(id,pid,nom,pre,ec);
  $('#input_'+id).val('');
}
function addProductoToMesa(mesa,id,nombre,precio,esCocina,qty=1,enviado=0){
  const lista=$('#productos_mesa_'+mesa);
  let li = lista.find('li').filter(function(){ return $(this).data('id')==id && !$(this).data('enviado'); });
  if(li.length){
    const newQty=(parseInt(li.data('qty'))||1)+qty;
    if(newQty<=0) li.remove(); else{li.data('qty',newQty).find('.qty').text(newQty);}
  }else if(qty>0){
    li=$(`
      <li class="list-group-item d-flex justify-content-between align-items-center ${enviado ? 'opacity-50' : ''}" data-id="${id}" data-precio="${precio}" data-nombre="${nombre}" data-cocina="${esCocina}" data-qty="${qty}" data-enviado="${enviado}">
        <span><strong class="nombre">${nombre}</strong><small class="text-muted"> - ${money(precio)}</small></span>
        <div class="d-flex align-items-center qty-controls">
          <button type="button" class="btn btn-sm btn-outline-secondary btn-minus me-1">-</button>
          <span class="qty">${qty}</span>
          <button type="button" class="btn btn-sm btn-outline-secondary btn-plus ms-1">+</button>
          <button type="button" class="btn btn-sm btn-danger btn-del ms-2">✕</button>
        </div>
      </li>`);
    lista.append(li);
  }
  actualizarTicketMesa(mesa); saveMesaState(mesa);
}
$(document).on('click','.btn-plus',function(){const li=$(this).closest('li');addProductoToMesa(MESA_ID,li.data('id'),li.data('nombre'),parseFloat(li.data('precio')),li.data('cocina'),1);});
$(document).on('click','.btn-minus',function(){const li=$(this).closest('li');addProductoToMesa(MESA_ID,li.data('id'),li.data('nombre'),parseFloat(li.data('precio')),li.data('cocina'),-1);});
$(document).on('click','.btn-del',function(){$(this).closest('li').remove();actualizarTicketMesa(MESA_ID);saveMesaState(MESA_ID);});

// ---------- TICKET ----------
function actualizarTicketMesa(id){
  let total=0,detalle=[];
  $('#productos_mesa_'+id+' li').each(function(){
    const p=parseFloat($(this).data('precio')),q=parseInt($(this).data('qty'))||1,n=$(this).data('nombre');
    total+=p*q;detalle.push(n+' x'+q);
  });
  const box=$('#ticket_mesa_'+id);
  box.find('div:eq(1)').html('Productos: '+(detalle.length?detalle.join(', '):'-'));
  box.find('div:eq(2)').html('Total: '+money(total));
  updateCocinaBlock(id);
}

// ---------- COCINA ----------
function updateCocinaBlock(id){
  const list=$('#productos_mesa_'+id+' li');
  const pend=list.filter(function(){return $(this).data('cocina')==1 && !$(this).data('enviado');});
  const bloc=$('#bloque_cocina_'+id);
  if(!pend.length){bloc.empty();return;}
  let html='<div class="alert alert-warning p-2"><div class="fw-bold mb-1"><i class="fas fa-utensils me-1"></i>Para cocina</div><ul class="mb-2">';
  pend.each(function(){html+='<li>'+$(this).data('nombre')+' x'+$(this).data('qty')+'</li>';});
  html+='</ul><button class="btn btn-sm btn-primary" id="btnEnviarCocina"><i class="fas fa-paper-plane me-1"></i>Enviar</button></div>';
  bloc.html(html);
  $('#btnEnviarCocina').off('click').on('click',function(){
    const ids=[];pend.each(function(){ids.push($(this).data('id'));});
    $(this).prop('disabled',true);
    fetch('ajax/enviar_cocina.php',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({mesa_id:MESA_ID,ids})})
      .then(r=>r.json()).then(res=>{
        if(res.ok){
// === PATCH: guardar ID real de comanda ===
currentComandaId = res.comanda_id;
localStorage.setItem('mesa_'+MESA_ID+'_comanda', currentComandaId);
// === FIN PATCH ===
pend.each(function(){$(this).data('enviado',1).attr('data-enviado','1').addClass('opacity-50');});
                   bloc.html('<div class="alert alert-success p-2"><i class="fas fa-check me-1"></i>Enviado a cocina</div>');
                   saveMesaState(MESA_ID);}
        else alert('Error al enviar');
      }).catch(()=>alert('Error'));
  });
}

// ---------- PERSISTENCIA ----------
function saveMesaState(id){
  const st={cliente:$('#form_mesa_'+id+' [name="cliente"]').val()||'',hora:$('#form_mesa_'+id+' [name="hora"]').val()||'',productos:[]};
  $('#productos_mesa_'+id+' li').each(function(){
    const qty=parseInt($(this).data('qty'))||0;if(qty<=0)return;
    st.productos.push({id: $(this).data('id'), nombre: $(this).data('nombre'), precio: $(this).data('precio'), es_cocina: $(this).data('cocina'), qty: qty, enviado: $(this).data('enviado') ? 1 : 0});
  });
  localStorage.setItem(LS_KEY(id),JSON.stringify(st));
}
function loadMesaState(id){
  const raw=localStorage.getItem(LS_KEY(id));if(!raw)return;
  try{
    const st=JSON.parse(raw);
    $('#form_mesa_'+id+' [name="cliente"]').val(st.cliente);
    $('#form_mesa_'+id+' [name="hora"]').val(st.hora);
    st.productos.forEach(p=>addProductoToMesa(id,p.id,p.nombre,parseFloat(p.precio),p.es_cocina,p.qty,p.enviado));
  }catch(e){}
}

// ---------- COBRO ----------
function getProductosMesa(id){
  const m={};
  $('#productos_mesa_'+id+' li').each(function(){
    const pid=$(this).data('id'),precio=parseFloat($(this).data('precio')),qty=parseInt($(this).data('qty'))||1;
    if(!m[pid]) m[pid]={id:pid,precio:precio,cantidad:qty};
    else m[pid].cantidad+=qty;
  });
  return Object.values(m);
}

function abrirModalCobroMesa(id){
  const total=parseFloat($('#ticket_mesa_'+id+' div:last-child').text().replace(/[^0-9.,]/g,'').replace(',','.'))||0;
  const prods=getProductosMesa(id);
  if(prods.length===0){alert('Mesa sin productos');return;}

  const modalContent=$('#modalCobroMesa .modal-content').html(`
    <div class="p-3">
      <form id="formCobroMesa">
        <input type="hidden" name="mesa_id" value="${id}">
        <input type="hidden" name="monto"    value="${total.toFixed(2)}">
        <h5 class="mb-3">Cobro Mesa</h5>
        <div class="mb-2">
          <label>Total</label>
          <input type="text" class="form-control" value="${money(total)}" readonly>
        </div>
        <div class="mb-2">
          <label>Forma de pago</label>
          <select class="form-select" id="formaPago" name="forma_pago" required>
            <option value="">-- Seleccionar --</option>
            <option value="efectivo">Efectivo</option>
            <option value="transferencia">Transferencia</option>
            <option value="dividido">Dividido</option>
          </select>
        </div>
        <div class="row mb-2 d-none" id="dividido">
          <div class="col">
            <label>Efectivo</label>
            <input type="number" step="0.01" class="form-control" name="efectivo">
          </div>
          <div class="col">
            <label>Transferencia</label>
            <input type="number" step="0.01" class="form-control" name="transferencia">
          </div>
        </div>
        <div class="d-flex justify-content-between mt-3">
          <button type="submit" class="btn btn-success"><i class="fas fa-save me-1"></i>Confirmar cobro</button>
          <a id="verTicket" href="#" target="_blank" class="btn btn-outline-primary d-none"><i class="fas fa-receipt me-1"></i>Ver ticket</a>
        </div>
      </form>
    </div>`);

  new bootstrap.Modal('#modalCobroMesa').show();

  $('#formaPago').on('change',function(){ $('#dividido').toggleClass('d-none',this.value!=='dividido');});

  $('#formCobroMesa').on('submit',function(e){
    e.preventDefault();
    const fd=new FormData(this);
    const forma=fd.get('forma_pago');
    const totalNum=parseFloat(fd.get('monto'))||0;
    if(forma==='efectivo'){fd.set('efectivo',totalNum.toFixed(2));fd.set('transferencia','0.00');}
    else if(forma==='transferencia'){fd.set('transferencia',totalNum.toFixed(2));fd.set('efectivo','0.00');}
    fd.append('productos_json',JSON.stringify(prods));
    const btn=this.querySelector('button[type="submit"]');btn.disabled=true;

    fetch('ajax/guardar_cobro_mesa.php',{method:'POST',body:fd})
    .then(r=>r.json())
    .then(data=>{
      if(data.success && data.ticket_id){
        $('#modalCobroMesa .modal-content').html(`
          <div class="p-3 text-center">
            <h5 class="text-success mb-3"><i class="fas fa-check-circle me-2"></i>Cobro registrado</h5>
            <div class="d-flex justify-content-center gap-3">
              <button class="btn btn-primary" onclick="window.open('ver_ticket_mesa.php?id=${data.ticket_id}', '_blank')">
                <i class="fas fa-eye me-1"></i>Ver Ticket
              </button>
              <button class="btn btn-secondary" onclick="window.open('ver_ticket_mesa.php?id=${data.ticket_id}&print=1','_blank')">
                <i class="fas fa-print me-1"></i>Imprimir
              </button>
              <button class="btn btn-success" onclick="finalizarMesa(${id})">
                <i class="fas fa-check me-1"></i>Finalizar
              </button>
            </div>
          </div>
        `);
      }else{
        alert('❌ Error: '+(data.error||'desconocido'));
        btn.disabled=false;
      }
    })
    .catch(()=>{alert('Error al guardar');btn.disabled=false;});
  });
}

function finalizarMesa(id){
  localStorage.removeItem('mesa_'+MESA_ID+'_comanda');
  currentComandaId = null;
  borrarComentariosMesa(id);           // ⬅️ limpia el chat
  localStorage.removeItem(LS_KEY(id)); // limpia productos / ticket
  location.reload();                   // recarga “a cero”
}


$(document).ready(()=>{loadMesaState(MESA_ID);actualizarTicketMesa(MESA_ID);});
</script>

<!-- Modal Comentarios -->
<div class="modal fade" id="modalComentario" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header py-2">
        <h5 class="modal-title m-0">Comentarios Mesa <?= $mesa_id ?></h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <!-- Se llena por JS -->
      </div>
    </div>
  </div>
</div>

<script>
const KEY_COM = id => `mesa_${id}_chat`;

/* Abre modal y pinta conversación */
function abrirModalComentario(id){
  pintarComentarios(id);
  new bootstrap.Modal(document.getElementById('modalComentario')).show();
}

/* Pinta mensajes y input */
function pintarComentarios(id){
  const arr = JSON.parse(localStorage.getItem(KEY_COM(id)) || '[]');
  let html = arr.map(c => `
    <div class="d-flex mb-2">
      <div class="bg-light p-2 rounded flex-grow-1">${escapeHtml(c.texto)}</div>
      <small class="text-muted ms-2">${c.fecha}</small>
    </div>`).join('');

  html += `
    <div class="input-group mt-3">
      <input type="text" id="nuevoComentario" class="form-control" placeholder="Escribir..." autocomplete="off">
      <button class="btn btn-primary" onclick="guardarComentario(${id})">Enviar</button>
    </div>`;

  document.querySelector('#modalComentario .modal-body').innerHTML = html;
}

/* Guarda nuevo mensaje */
function guardarComentario(id){
  const inp = document.getElementById('nuevoComentario');
  if(!inp) return;
  const txt = inp.value.trim();
  if(!txt) return;
  const arr = JSON.parse(localStorage.getItem(KEY_COM(id)) || '[]');
  const fecha = new Date().toLocaleTimeString('es-AR',{hour:'2-digit',minute:'2-digit'});
  arr.push({texto: txt, fecha});
  localStorage.setItem(KEY_COM(id), JSON.stringify(arr));
  pintarComentarios(id);
  inp.focus();
}

/* Limpiar chat al cerrar la mesa */
function borrarComentariosMesa(id){
  localStorage.removeItem(KEY_COM(id));
}

/* Escapar HTML para evitar XSS */
function escapeHtml(str){
  return str.replace(/[&<>"']/g, s => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[s]));
}
/* Guarda nuevo mensaje y lo envía al servidor */
function guardarComentario(id){
  const inp = document.getElementById('nuevoComentario');
  const txt = inp.value.trim();
  if(!txt) return;

  /* 1) Guarda local */
  const arr = JSON.parse(localStorage.getItem(KEY_COM(id))||'[]');
  const fecha = new Date().toLocaleTimeString('es-AR',{hour:'2-digit',minute:'2-digit'});
  arr.push({texto:txt,fecha});
  localStorage.setItem(KEY_COM(id),JSON.stringify(arr));
  pintarComentarios(id);

  /* 2) Envía al backend */
  fetch('ajax/guardar_comentario.php',{
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:`mesa_id=${id}&comanda_id=${currentComandaId||0}&texto=${encodeURIComponent(txt)}`
  }).catch(()=>{});
}

</script>

</body>
</html>