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

/* ---------- COMANDAS (todas) ---------- */
$sqlComandas = "
    SELECT id,
           mesa_id,
           estado,
           DATE_FORMAT(hora,'%H:%i')  AS hora,
           detalle
    FROM   comandas_cocina
    ORDER  BY hora ASC";
$res = mysqli_query($con,$sqlComandas);
$comandas = [];
while($row = mysqli_fetch_assoc($res)){
    $row['detalle'] = json_decode($row['detalle'], true);
    $comandas[]     = $row;
}

/* ---------- COMENTARIOS (agrupados por comanda) ---------- */
$comments = [];
$resC = mysqli_query(
    $con,
    "SELECT comanda_id,
            texto,
            DATE_FORMAT(fecha,'%H:%i') AS hora
     FROM   comentarios_mesa
     WHERE  comanda_id IS NOT NULL
     ORDER  BY id ASC"
);
while($cm = mysqli_fetch_assoc($resC)){
    $cid = intval($cm['comanda_id']);
    if(!isset($comments[$cid])) $comments[$cid] = [];
    $comments[$cid][] = $cm;
}

/* ---------- Salida HTML ---------- */
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Comandas 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{--pri:#ff6b35;--ok:#43aa8b;--warn:#f8961e;--sec:#004e89;}
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;}
.header h4{color:var(--pri);font-weight:700}
.section{margin-bottom:2rem;}
.section h5{font-size:1rem;color:#333;margin-bottom:.5rem;}
.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:1rem}
.card{border-left:4px solid var(--pri);border-radius:8px;background:#fff;padding:.8rem;display:flex;flex-direction:column;position:relative;box-shadow:0 2px 6px rgba(0,0,0,.05);}
.mesa{background:var(--pri);color:#fff;font-size:.7rem;padding:.25rem .6rem;border-radius:50px;font-weight:600;}
.hora{font-size:.75rem;color:#718096;display:flex;align-items:center;gap:.25rem;}
ul{list-style:none;margin:0 0 .8rem 0;padding:0}
li{display:flex;justify-content:space-between;font-size:.85rem;padding:.3rem 0;border-bottom:1px dashed #f0f0f0;}
li:last-child{border-bottom:none}
.qty{color:var(--pri);font-weight:600;margin-right:.3rem}
.nota{font-size:.75rem;color:#444;margin:2px 0;padding-left:1.2rem;position:relative;}
.nota::before{content:"💬";position:absolute;left:0;top:0;}
.foot{display:flex;gap:.5rem;justify-content:flex-end;padding-top:.5rem;border-top:1px solid #f0f0f0;}
.btn-act{border-radius:6px;font-size:.75rem;padding:.3rem .6rem;border:1px solid transparent;display:inline-flex;align-items:center;}
.process{background:rgba(255,167,0,.15);color:var(--warn);}
.process:hover{background:var(--warn);color:#fff}
.dispatch{background:rgba(67,170,139,.15);color:var(--ok);}
.dispatch:hover{background:var(--ok);color:#fff}
.print{background:rgba(0,78,137,.15);color:var(--sec);}
.print:hover{background:var(--sec);color:#fff}
.alerta{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 .btn-close{font-size:.6rem;line-height:1;}
#toast{display:none;position:fixed;top:20px;right:20px;background:var(--pri);color:#fff;padding:15px 20px;border-radius:8px;z-index:1000;box-shadow:0 4px 12px rgba(0,0,0,.15);}
@keyframes blink { 50% { opacity:.4; } }
.blink { animation: blink 1s linear infinite; }
</style>
</head>
<body>
  <div class="header">
    <h4><i class="bi bi-fire me-2"></i>Comandas Cocina</h4>
    <small class="text-muted"><i class="bi bi-clock-history me-1"></i><?php echo date('H:i'); ?></small>
  </div>

  <!-- Pendientes -->
  <div class="section">
    <h5>Pendientes</h5>
    <div class="grid" id="gridPend"></div>
  </div>

  <!-- En proceso -->
  <div class="section">
    <h5>En proceso</h5>
    <div class="grid" id="gridProc"></div>
  </div>

  <!-- Historial -->
  <div class="section">
    <h5>Despachadas (historial)</h5>
    <div class="grid" id="gridDesp"></div>
  </div>

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

<script>
/* ---------- datos iniciales desde PHP ---------- */
const COMANDAS_INI    = <?php echo json_encode($comandas,   JSON_UNESCAPED_UNICODE); ?>;
const COMENTARIOS_INI = <?php echo json_encode($comments,   JSON_UNESCAPED_UNICODE); ?>;

/* ---------- helpers ---------- */
function colorMesa(n){ const hue=(n*37)%360; return `hsl(${hue} 80% 45%)`; }

/* ---------- estado local ---------- */
let hashPrev="";
let pendAlert   = JSON.parse(localStorage.getItem('alertas_pendientes')||'[]');
let vistasCom   = JSON.parse(localStorage.getItem('comandas_vistas')   ||'[]');
function saveLS(){
  localStorage.setItem('alertas_pendientes',JSON.stringify(pendAlert));
  localStorage.setItem('comandas_vistas',   JSON.stringify(vistasCom));
}

/* ---------- sonido & alertas ---------- */
const beep=document.getElementById('sonido');
function toast(){
    const t=document.getElementById('toast');
    t.style.display='block';
    setTimeout(()=>t.style.display='none',3000);
    beep.currentTime=0; beep.play().catch(()=>{});
}
function addAlert(card){
  if(card.querySelector('.alerta')) return;
  const box=document.createElement('div'); box.className='alerta';
  box.innerHTML='🆕 Nueva comanda <button type="button" class="btn-close"></button>';
  box.querySelector('.btn-close').onclick=()=>{
      box.remove();
      card.classList.remove('blink');
      pendAlert = pendAlert.filter(i=>i!==card.dataset.id);
      saveLS();
  };
  card.prepend(box); card.classList.add('blink');
}

/* ---------- acciones ---------- */
function cambiarEstado(id,estado){
  fetch('ajax/marcar_estado_comanda.php',{
      method:'POST',
      headers:{'Content-Type':'application/x-www-form-urlencoded'},
      body:`id=${encodeURIComponent(id)}&estado=${encodeURIComponent(estado)}`
  })
  .then(r=>r.json())
  .then(()=>{
      // Refrescamos toda la vista para reflejar el cambio de forma inmediata
      location.reload();
  })
  .catch(console.error);
}
function imprimir(id){
  const card=document.querySelector('.card[data-id="'+id+'"]');
  if(!card) return;
  const w=window.open('','_blank','width=400,height=600');
  const css=`<style>
      body{font-family:Segoe UI,Roboto,Helvetica,sans-serif;padding:10px;}
      .mesa{font-size:1.2rem;margin-bottom:6px;}
      ul{list-style:none;padding:0;margin:0 0 8px 0;}
      li{font-size:1rem;}
      .nota{font-size:.9rem;color:#555;margin-bottom:4px;}
    </style>`;
  w.document.write(css + card.outerHTML);
  w.document.close();
  w.focus();
  w.print();
}

/* ---------- render helpers ---------- */
function buildCard(c,comments){
    const col=colorMesa(c.mesa_id);
    const card=document.createElement('div');
    card.className='card';
    card.dataset.id=c.id;
    card.style.borderLeftColor=col;

    const productosHTML = c.detalle.map(p=>
      `<li><div><span class="qty">${p.cantidad}x</span>${p.nombre}</div></li>`
    ).join('');

    const comentariosHTML = (comments[c.id]||[]).slice(-3).map(cm=>
      `<div class="nota">${cm.texto} <small class="text-muted">${cm.hora}</small></div>`
    ).join('');

    let buttons='';
    if(c.estado==0){
        buttons+=`<button class="btn-act process" title="En proceso" onclick="cambiarEstado(${c.id},1)"><i class="bi bi-hourglass-split"></i></button>`;
    }
    if(c.estado<=1){
        buttons+=`<button class="btn-act dispatch" title="Despachada" onclick="cambiarEstado(${c.id},2)"><i class="bi bi-check-circle"></i></button>`;
    }
    buttons+=`<button class="btn-act print" title="Imprimir" onclick="imprimir(${c.id})"><i class="bi bi-printer"></i></button>`;

    card.innerHTML=`
      <div class="d-flex justify-content-between align-items-center mb-1">
         <span class="mesa" style="background:${col}">MESA ${c.mesa_id}</span>
         <span class="hora"><i class="bi bi-clock"></i> ${c.hora}</span>
      </div>
      <ul>${productosHTML}</ul>
      ${comentariosHTML}
      <div class="foot">${buttons}</div>`;

    const idStr=String(c.id);
    if(c.estado==0 && !vistasCom.includes(idStr)){ vistasCom.push(idStr); pendAlert.push(idStr); saveLS(); }
    if(pendAlert.includes(idStr)) addAlert(card);
    return card;
}
function render(comandas,comments){
  const gridPend=document.getElementById('gridPend');
  const gridProc=document.getElementById('gridProc');
  const gridDesp=document.getElementById('gridDesp');
  gridPend.innerHTML=gridProc.innerHTML=gridDesp.innerHTML='';

  comandas.forEach(c=>{
     const card=buildCard(c,comments);
     if(c.estado==0)       gridPend.appendChild(card);
     else if(c.estado==1)  gridProc.appendChild(card);
     else if(c.estado==2)  gridDesp.appendChild(card);
  });
}

/* ---------- polling ---------- */
function getComandas(){
  fetch('ver_cocina_ajax.php')
    .then(r=>r.json())
    .then(js=>{
      const {comandas,comentarios} = js;
      const newPend = comandas.filter(c=>c.estado==0 && !vistasCom.includes(String(c.id)));
      if(newPend.length) toast();

      // update vistas para nuevos pendientes
      newPend.forEach(c=>{
          vistasCom.push(String(c.id));
          pendAlert.push(String(c.id));
      });

      const newHash = JSON.stringify(comandas)+JSON.stringify(comentarios);
      if(newHash===hashPrev) return;
      hashPrev=newHash;
      render(comandas,comentarios);
      saveLS();
    })
    .catch(console.error);
}

/* ---------- init ---------- */
render(COMANDAS_INI,COMENTARIOS_INI);
hashPrev = JSON.stringify(COMANDAS_INI)+JSON.stringify(COMENTARIOS_INI);
// Actualización automática cada 10 segundos
setInterval(getComandas,10000);
</script>
</body>
</html>
