<?php
require_once 'conexion.php';
date_default_timezone_set('America/Argentina/Buenos_Aires');
header('Content-Type: application/json');

/* ---------- COMANDAS (todas) ---------- */
$res = mysqli_query(
    $con,
    "SELECT id,
            mesa_id,
            estado,
            DATE_FORMAT(hora,'%H:%i') AS hora,
            detalle
     FROM   comandas_cocina
     ORDER  BY hora ASC"
);
$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;
}

echo json_encode([
    'comandas'   => $comandas,
    'comentarios'=> $comments
], JSON_UNESCAPED_UNICODE);
