
<?php
require_once 'conexion.php';
date_default_timezone_set('America/Argentina/Buenos_Aires');

$res = mysqli_query($con, "SELECT * FROM comandas_cocina WHERE estado IN (0,1) ORDER BY hora ASC");
$comandas_actuales = mysqli_num_rows($res);
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Comandas de Cocina</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
  <style>
    :root{
      --primary:#ff6b35;
      --secondary:#004e89;
      --success:#43aa8b;
      --warning:#f8961e;
    }
    body{
      background:#f0f2f5;
      font-family:'Segoe UI',Roboto,'Helvetica Neue',sans-serif;
      padding:1rem;
    }
    .header{display:flex;justify-content:space-between;align-items:center;margin-bottom:1rem;padding-bottom:.5rem;border-bottom:1px solid #e0e6ed;}
    .header h4{color:var(--primary);font-weight:700;margin:0;}
    .comandas-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:1rem;}
    .comanda-card{border-left:4px solid var(--primary);border-radius:8px;background:#fff;padding:.8rem;box-shadow:0 2px 6px rgba(0,0,0,.05);display:flex;flex-direction:column;position:relative;}
    .mesa-badge{background:var(--primary);color:#fff;font-size:.7rem;padding:.25rem .6rem;border-radius:50px;font-weight:600;}
    .comanda-time{font-size:.75rem;color:#718096;display:flex;align-items:center;gap:.2rem;}
    .product-list{list-style:none;padding:0;margin:0 0 .8rem 0;flex-grow:1;}
    .product-item{display:flex;justify-content:space-between;font-size:.85rem;padding:.3rem 0;border-bottom:1px dashed #f0f0f0;}
    .product-item:last-child{border-bottom:none;}
    .product-quantity{color:var(--primary);font-weight:600;margin-right:.3rem;}
    .product-notes{font-size:.7rem;color:#666;margin-left:.5rem;}
    .comanda-footer{display:flex;gap:.5rem;justify-content:flex-end;padding-top:.5rem;border-top:1px solid #f0f0f0;}
    .btn-action{border-radius:6px;font-size:.75rem;padding:.3rem .6rem;border:1px solid transparent;display:inline-flex;align-items:center;}
    .btn-process{background:rgba( var(--warning), .1);color:var(--warning);}
    .btn-process:hover{background:var(--warning);color:#fff;}
    .btn-dispatch{background:rgba(var(--success), .1);color:var(--success);}
    .btn-dispatch:hover{background:var(--success);color:#fff;}
    .btn-print{background:rgba(var(--secondary), .1);color:var(--secondary);}
    .btn-print:hover{background:var(--secondary);color:#fff;}
    /* Alerta dentro de cada card */
    .alerta-nueva-comanda{background:#fff3cd;border:1px solid #ffeeba;border-radius:5px;font-size:.8rem;padding:.25rem .5rem;margin-bottom:.4rem;display:flex;justify-content:space-between;align-items:center;}
    .alerta-nueva-comanda .btn-close{font-size:.6rem;line-height:1;}
    /* Notificación flotante */
    #toastNueva{display:none;position:fixed;top:20px;right:20px;background:var(--primary);color:#fff;padding:15px 20px;border-radius:8px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,.15);}
  </style>
</head>
<body>
  <div class="header">
    <h4><i class="bi bi-fire me-2"></i>Comandas Cocina</h4>
    <div class="text-muted small"><i class="bi bi-clock-history me-1"></i><?=date('H:i')?></div>
  </div>

  <div class="comandas-grid" id="comandas-container">
    <?php if(mysqli_num_rows($res)): ?>
      <?php while($c = mysqli_fetch_assoc($res)): ?>
        <?php $productos = json_decode($c['detalle'],true); ?>
        <div class="comanda-card" data-id="<?=$c['id']?>">
          <div class="comanda-header d-flex justify-content-between">
            <span class="mesa-badge">MESA <?=$c['mesa_id']?></span>
            <span class="comanda-time"><i class="bi bi-clock"></i><?=date('H:i',strtotime($c['hora']))?></span>
          </div>
          <ul class="product-list">
            <?php foreach($productos as $p): ?>
            <li class="product-item">
              <div><span class="product-quantity"><?=$p['cantidad']?>x</span><?=$p['nombre']?><span class="product-notes"><?=empty($p['notas'])?'':'('.htmlspecialchars($p['notas']).')'?></span></div>
            </li>
            <?php endforeach; ?>
          </ul>
          <div class="comanda-footer">
            <?php if($c['estado']==0): ?>
            <button class="btn-action btn-process" onclick="cambiarEstado(<?=$c['id']?>,1)" title="En proceso"><i class="bi bi-hourglass-split"></i></button>
            <?php endif; ?>
            <button class="btn-action btn-dispatch" onclick="cambiarEstado(<?=$c['id']?>,2)" title="Despachar"><i class="bi bi-check-circle"></i></button>
            <button class="btn-action btn-print" onclick="imprimirComanda(<?=$c['id']?>)" title="Imprimir"><i class="bi bi-printer"></i></button>
          </div>
        </div>
      <?php endwhile; ?>
    <?php else: ?>
      <div class="alert alert-info">No hay comandas pendientes</div>
    <?php endif; ?>
  </div>

  <div id="toastNueva"><i class="bi bi-bell-fill me-2"></i>¡+1 comanda nueva!</div>
  <audio id="audioComanda" src="/sonido/comanda.mp3" preload="auto"></audio>

<script>
let ultimaCantidad = <?=$comandas_actuales?>;
let hashAnterior = "";
let alertasPendientes = JSON.parse(localStorage.getItem('alertas_pendientes')||'[]');
let comandasVistas  = JSON.parse(localStorage.getItem('comandas_vistas')||'[]');

/* Helpers */
function guardarLocal() {
  localStorage.setItem('alertas_pendientes', JSON.stringify(alertasPendientes));
  localStorage.setItem('comandas_vistas',   JSON.stringify(comandasVistas));
}
function toast(){
  const t=document.getElementById('toastNueva');
  t.style.display='block';
  setTimeout(()=>t.style.display='none',3000);
  document.getElementById('audioComanda').play().catch(()=>{});
}
function agregarAlerta(card){
  if(card.querySelector('.alerta-nueva-comanda')) return;
  const div=document.createElement('div');
  div.className='alerta-nueva-comanda';
  div.innerHTML=`🔔 Nueva comanda <button type="button" class="btn-close"></button>`;
  div.querySelector('.btn-close').addEventListener('click',()=>{
     div.remove();
     const id=card.dataset.id;
     alertasPendientes=alertasPendientes.filter(x=>x!==id);
     guardarLocal();
  });
  card.prepend(div);
}

/* Inicial: marcar vistas y poner alertas pendientes */
document.addEventListener('DOMContentLoaded',()=>{
  document.querySelectorAll('.comanda-card').forEach(card=>{
     const id=card.dataset.id;
     if(!comandasVistas.includes(id)){
        comandasVistas.push(id);
        alertasPendientes.push(id);
     }
     if(alertasPendientes.includes(id)) agregarAlerta(card);
  });
  guardarLocal();
  /* Hash inicial */
  hashAnterior = generarHash(document.querySelectorAll('.comanda-card'));
});

/* Hash builder */
function generarHash(nodeList){
  return Array.from(nodeList).map(c=>c.dataset.id+'-'+c.querySelector('.product-list').innerHTML).join('|');
}

/* Ajax polling */
setInterval(actualizarComandas,5000);

function actualizarComandas(){
  fetch('ver_cocina_ajax.php')
    .then(r=>r.json())
    .then(data=>{
       const nuevoHash = data.map(c=>c.id+'-'+c.detalle).join('|');
       if(nuevoHash===hashAnterior) return;
       if(data.length>ultimaCantidad) toast();
       /* detectar nuevos para alertas */
       data.forEach(c=>{
          const id=String(c.id);
          if(!comandasVistas.includes(id)){
             comandasVistas.push(id);
             alertasPendientes.push(id);
          }
       });
       guardarLocal();
       renderComandas(data);
       ultimaCantidad=data.length;
       hashAnterior=nuevoHash;
    });
}

/* Render */
function renderComandas(lista){
  const container=document.getElementById('comandas-container');
  container.innerHTML='';
  lista.forEach(c=>{
     const productos=JSON.parse(c.detalle);
     const hora=new Date(c.hora).toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
     const card=document.createElement('div');
     card.className='comanda-card';
     card.dataset.id=c.id;
     card.innerHTML=`
      <div class="comanda-header d-flex justify-content-between">
        <span class="mesa-badge">MESA ${c.mesa_id}</span>
        <span class="comanda-time"><i class="bi bi-clock"></i>${hora}</span>
      </div>
      <ul class="product-list">
        ${productos.map(p=>`<li class="product-item"><div><span class="product-quantity">${p.cantidad}x</span>${p.nombre}${p.notas?'<span class="product-notes">('+p.notas+')</span>':''}</div></li>`).join('')}
      </ul>
      <div class="comanda-footer">
        ${c.estado==0?`<button class="btn-action btn-process" onclick="cambiarEstado(${c.id},1)" title="En proceso"><i class="bi bi-hourglass-split"></i></button>`:''}
        <button class="btn-action btn-dispatch" onclick="cambiarEstado(${c.id},2)" title="Despachar"><i class="bi bi-check-circle"></i></button>
        <button class="btn-action btn-print"   onclick="imprimirComanda(${c.id})"  title="Imprimir"><i class="bi bi-printer"></i></button>
      </div>`;
     if(alertasPendientes.includes(String(c.id))) agregarAlerta(card);
     container.appendChild(card);
  });
}

/* Cambiar estado */
function cambiarEstado(id,estado){
  fetch('ajax/marcar_estado_comanda.php',{
    method:'POST',
    headers:{'Content-Type':'application/x-www-form-urlencoded'},
    body:`id=${id}&estado=${estado}`
  }).then(r=>{if(r.ok) actualizarComandas();});
}

/* Imprimir */
function imprimirComanda(id){
  const card=document.querySelector(`.comanda-card[data-id="${id}"]`);
  if(!card) return;
  const html=`
  <!DOCTYPE html>
  <html><head>
    <meta charset="utf-8">
    <title>Comanda #${id}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
      body{font-family:Arial,sans-serif;font-size:14px;padding:1rem;}
      h2{font-size:1.2rem;text-align:center;margin-bottom:10px;}
      ul{list-style:none;padding:0;margin:0;}
      li{display:flex;justify-content:space-between;margin-bottom:4px;}
      .qty{color:#ff6b35;font-weight:bold;}
    </style>
  </head><body>
    <h2>COMANDA #${id}</h2>
    <strong>${card.querySelector('.mesa-badge').textContent}</strong><br>
    <small>${card.querySelector('.comanda-time').textContent}</small>
    <hr>
    <ul>
      ${card.querySelector('.product-list').innerHTML}
    </ul>
  </body></html>`;
  const w=window.open('','_blank','width=400,height=600');
  w.document.write(html);
  w.document.close();
  w.focus();
  setTimeout(()=>w.print(),300);
}
</script>
</body>
</html>
