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

/* ---------- Parámetros ---------- */
$hoy        = date('Y-m-d');
$inicio_raw = $_GET['inicio'] ?? ($hoy.'T00:00');
$fin_raw    = $_GET['fin']    ?? date('Y-m-d\TH:i');

$inicio = str_replace('T', ' ', $inicio_raw) . ':00';
$fin    = str_replace('T', ' ', $fin_raw)    . ':59';

/* ---------- 1) Resumen ---------- */
$sqlResumen = "
  SELECT
    COUNT(*)                       AS cant_tickets,
    COALESCE(SUM(total),0)         AS total_fact,
    COALESCE(SUM(total)/NULLIF(COUNT(*),0),0) AS ticket_prom,
    COALESCE(SUM(efectivo),0)      AS total_efec,
    COALESCE(SUM(transferencia),0) AS total_transf
  FROM tickets_mesa
  WHERE fecha BETWEEN ? AND ?
";
$st = $con->prepare($sqlResumen);
$st->bind_param('ss', $inicio, $fin);
$st->execute();
$resumen = $st->get_result()->fetch_assoc();

/* ---------- Mesa top ---------- */
$sqlTopMesa = "
  SELECT mesa_id, SUM(total) tot
  FROM tickets_mesa
  WHERE fecha BETWEEN ? AND ?
  GROUP BY mesa_id
  ORDER BY tot DESC
  LIMIT 1
";
$sm = $con->prepare($sqlTopMesa);
$sm->bind_param('ss', $inicio, $fin);
$sm->execute();
$topMesa = $sm->get_result()->fetch_assoc();

/* ---------- Stock & vendidos ---------- */
$sqlStock = "
  SELECT pm.id, pm.nombre, pm.stock,
         COALESCE(SUM(tmd.cantidad),0) AS vendidos
  FROM productos_mesas pm
  LEFT JOIN tickets_mesa_detalle tmd ON tmd.producto_id = pm.id
  LEFT JOIN tickets_mesa tm          ON tm.id = tmd.ticket_id
       AND tm.fecha BETWEEN ? AND ?
  GROUP BY pm.id
  ORDER BY vendidos DESC, pm.nombre
";
$ss = $con->prepare($sqlStock);
$ss->bind_param('ss', $inicio, $fin);
$ss->execute();
$stockRows = $ss->get_result()->fetch_all(MYSQLI_ASSOC);

/* ---------- Tickets ---------- */
$sqlTickets = "
  SELECT id, mesa_id, fecha, total
  FROM tickets_mesa
  WHERE fecha BETWEEN ? AND ?
  ORDER BY fecha DESC
";
$tk = $con->prepare($sqlTickets);
$tk->bind_param('ss', $inicio, $fin);
$tk->execute();
$tickets = [];
$ticketDetalles = [];

$resTk = $tk->get_result();
while ($row = $resTk->fetch_assoc()) {
    // detalle individual (usa tmd.precio, alias precio_unitario)
    $qd = "
      SELECT pm.nombre,
             tmd.cantidad,
             tmd.precio AS precio_unitario
      FROM tickets_mesa_detalle tmd
      JOIN productos_mesas pm ON pm.id = tmd.producto_id
      WHERE tmd.ticket_id = ?
    ";
    $sd = $con->prepare($qd);
    $sd->bind_param('i', $row['id']);
    $sd->execute();
    $det = $sd->get_result()->fetch_all(MYSQLI_ASSOC);

    $tickets[] = $row;
    $ticketDetalles[$row['id']] = [
        'mesa_id' => $row['mesa_id'],
        'fecha'   => date('d/m H:i', strtotime($row['fecha'])),
        'total'   => number_format($row['total'], 2, ',', '.'),
        'det'     => $det
    ];
}
?>
<!doctype html><html lang="es"><head>
<meta charset="utf-8">
<title>Buscar tickets</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<style>.negativo{color:#dc3545;font-weight:600}</style>
</head><body class="bg-light">
<div class="container py-4">

<h2 class="mb-4">Tickets</h2>

<!-- Filtro -->
<form class="row g-3 mb-4">
  <div class="col-auto">
    <label class="form-label">Desde</label>
    <input type="datetime-local" name="inicio" class="form-control"
           value="<?= htmlspecialchars($inicio_raw) ?>">
  </div>
  <div class="col-auto">
    <label class="form-label">Hasta</label>
    <input type="datetime-local" name="fin" class="form-control"
           value="<?= htmlspecialchars($fin_raw) ?>">
  </div>
  <div class="col-auto align-self-end">
    <button class="btn btn-primary">Filtrar</button>
  </div>
</form>

<!-- Resumen -->

<!-- Mesas cerradas -->
<h4 class="mt-5">Mesas cerradas (<?= count($tickets) ?>)</h4>

<?php if(!$tickets): ?>
  <p>No hay tickets en el rango.</p>
<?php else: ?>
  <div class="row g-3 align-items-end mb-3">
    <div class="col-md-6">
      <label class="form-label">Seleccioná un ticket</label>
      <select id="ticketSelect" class="form-select">
        <option value="">— Elegir —</option>
        <?php foreach($tickets as $t): ?>
          <option value="<?= $t['id'] ?>">
            Ticket #<?= $t['id'] ?> | Mesa <?= $t['mesa_id'] ?> | <?= date('d/m H:i', strtotime($t['fecha'])) ?> | $<?= number_format($t['total'],2,',','.') ?>
          </option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="col-md-2">
      <a id="verTicketLink" href="#" target="_blank" class="btn btn-secondary disabled w-100">Ver ticket</a>
    </div>
  </div>

  <!-- Detalle -->
  <div id="ticketDetalle" class="card d-none">
    <div class="card-header" id="ticketResumen"></div>
    <div class="card-body p-2">
      <table class="table table-sm mb-0">
        <thead><tr><th>Producto</th><th class="text-end">Cant.</th><th class="text-end">P.U.</th></tr></thead>
        <tbody id="ticketBody"></tbody>
      </table>
    </div>
  </div>
<?php endif; ?>

</div><!-- /container -->

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// datos de PHP -> JS
const ticketData = <?= json_encode($ticketDetalles, JSON_UNESCAPED_UNICODE) ?>;

const sel   = document.getElementById('ticketSelect');
const card  = document.getElementById('ticketDetalle');
const body  = document.getElementById('ticketBody');
const head  = document.getElementById('ticketResumen');
const link  = document.getElementById('verTicketLink');

sel.addEventListener('change', ()=>{
  const id = sel.value;
  if(!id){
    card.classList.add('d-none');
    link.classList.add('disabled'); link.href='#';
    return;
  }
  const t = ticketData[id];
  head.textContent = `Mesa ${t.mesa_id} | ${t.fecha} | $${t.total}`;
  body.innerHTML = t.det.map(d=>`
    <tr>
      <td>${d.nombre}</td>
      <td class="text-end">${d.cantidad}</td>
      <td class="text-end">$${parseFloat(d.precio_unitario).toFixed(2)}</td>
    </tr>`).join('');
  card.classList.remove('d-none');
  link.href = 'ver_ticket_mesa.php?id='+id;
  link.classList.remove('disabled');
});
</script>
</body></html>
