<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (function_exists('opcache_invalidate')) {
  opcache_invalidate(__DIR__ . '/verifica_cookie.php', true);
  opcache_invalidate(__DIR__ . '/includes/inc_menu.php', true);
}
session_start();
require 'conexao.php';
require 'config.php';
require_once __DIR__ . '/verifica_cookie.php';
require 'includes/inc_verifica_caixa.php';
require 'includes/limpar_session.php';

$praca = (isset($_COOKIE['pPraca'])) ? $_COOKIE['pPraca'] : '';

function truncar($str, $max, $sufixo = '..')
{
  if (function_exists('mb_strlen')) {
    if (mb_strlen($str) <= $max) return $str;
    return mb_substr($str, 0, $max - mb_strlen($sufixo)) . $sufixo;
  }
  if (strlen($str) <= $max) return $str;
  return substr($str, 0, $max - strlen($sufixo)) . $sufixo;
}

function formatarTempo($dataCadastro)
{
  if (empty($dataCadastro)) return '';
  $agora = new DateTime();
  $data  = new DateTime($dataCadastro);
  $diff  = $agora->diff($data);
  $minutos = ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
  if ($minutos < 60) {
    return $minutos . 'min';
  }
  $horas = floor($minutos / 60);
  if ($horas > 99) {
    return $horas . 'h';
  }
  $mins  = $minutos % 60;
  return $horas . 'h' . ($mins > 0 ? ' ' . $mins . 'min' : '');
}

function calcularMinutos($dataCadastro)
{
  if (empty($dataCadastro)) return 0;
  $agora = new DateTime();
  $data  = new DateTime($dataCadastro);
  $diff  = $agora->diff($data);
  return ($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i;
}

$pdo  = Conexao::getInstance();
$condicao = ($praca > 0) ? " AND praca = '{$praca}' " : '';
$sql = "SELECT mes_003, mes_001 FROM mesa WHERE sit_001 = 4 {$condicao} ORDER BY mes_001";
$stm = $pdo->prepare($sql);
$stm->execute();
$mesas = $stm->fetchAll(PDO::FETCH_OBJ);

$sql = 'SELECT b_reabrir_mesa_comanda FROM usuarios WHERE usu_001 = :id_usuario';
$stm = $pdo->prepare($sql);
$stm->bindValue(':id_usuario', isset($_COOKIE['id']) ? $_COOKIE['id'] : 0);
$stm->execute();
$autorizacao = $stm->fetch(PDO::FETCH_OBJ);

// Build mesa data with status
$mesaData = [];
foreach ($mesas as $mesa) {
  $link    = 'pedido.php?mesa=' . $mesa->mes_001 . '&tipo=M';
  $linkNovo = (EXIGE_CADASTRO_CLIENTE) ? 'cliente_pesquisa.php?mesa=' . $mesa->mes_001 . '&tipo=M' : $link;

  $stm = $pdo->prepare("SELECT v.sit_001, v.ven_001, COALESCE(v.cli_001, 0) as cli_001, COALESCE(v.ven_027, '') as ven_027, c.cli_002 as nome_cliente FROM venda v LEFT JOIN clientes c ON v.cli_001 = c.cli_001 WHERE v.sit_001 = 8 AND v.ven_025 = :id");
  $stm->execute([':id' => $mesa->mes_001]);
  $venda = $stm->fetch(PDO::FETCH_OBJ);

  if (!empty($venda)) {
    $status      = 'aberta';
    $back        = 'btn-red';
    $finalLink   = $link . '&venda=' . $venda->ven_001 . '&id_cliente=' . $venda->cli_001;
    $idVenda     = $venda->ven_001;
    $nomeCliente = (!empty($venda->cli_001) && $venda->cli_001 > 0 && !empty($venda->nome_cliente)) ? $venda->nome_cliente : $venda->ven_027;
    $stmTempo = $pdo->prepare("SELECT MAX(data_cadastro) as ultimo_pedido FROM vendaitem WHERE ven_001 = :venda AND sit_001 = 4");
    $stmTempo->execute([':venda' => $venda->ven_001]);
    $rowTempo = $stmTempo->fetch(PDO::FETCH_OBJ);
    $tempo = formatarTempo($rowTempo->ultimo_pedido ?? '');
    $tempoMinutos = calcularMinutos($rowTempo->ultimo_pedido ?? '');
  } else {
    $stm = $pdo->prepare("SELECT v.sit_001, v.ven_001, COALESCE(v.cli_001, 0) as cli_001, COALESCE(v.ven_027, '') as ven_027, c.cli_002 as nome_cliente FROM venda v LEFT JOIN clientes c ON v.cli_001 = c.cli_001 WHERE v.sit_001 = 21 AND v.ven_025 = :id");
    $stm->execute([':id' => $mesa->mes_001]);
    $venda = $stm->fetch(PDO::FETCH_OBJ);

    if (!empty($venda)) {
      $status      = 'pre-fechada';
      $back        = 'btn-yellow';
      $finalLink   = 'javascript:void(0)';
      $idVenda     = $venda->ven_001;
      $nomeCliente = (!empty($venda->cli_001) && $venda->cli_001 > 0 && !empty($venda->nome_cliente)) ? $venda->nome_cliente : $venda->ven_027;
      $stmTempo = $pdo->prepare("SELECT MAX(data_cadastro) as ultimo_pedido FROM vendaitem WHERE ven_001 = :venda AND sit_001 = 4");
      $stmTempo->execute([':venda' => $venda->ven_001]);
      $rowTempo = $stmTempo->fetch(PDO::FETCH_OBJ);
      $tempo = formatarTempo($rowTempo->ultimo_pedido ?? '');
      $tempoMinutos = calcularMinutos($rowTempo->ultimo_pedido ?? '');
    } else {
      $status      = 'livre';
      $back        = '';
      $finalLink   = $linkNovo;
      $idVenda     = '';
      $nomeCliente = '';
      $tempo       = '';
      $tempoMinutos = 0;
    }
  }

  $mesaData[] = [
    'numero'  => $mesa->mes_003,
    'id'      => $mesa->mes_001,
    'link'    => $finalLink,
    'back'    => $back,
    'status'  => $status,
    'idVenda' => $idVenda,
    'cliente' => $nomeCliente,
    'tempo'   => $tempo ?? '',
    'tempoMinutos' => $tempoMinutos ?? 0,
  ];
}
?>
<!DOCTYPE html>
<html>

<head>
  <title>Comanda Eletrônica</title>
  <?php require 'includes/inc_head.php'; ?>
  <style>
    .box-mesas {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(72px, 1fr));
      gap: 10px;
      padding: 8px 12px 12px;
    }

    @media (min-width: 600px) {
      .box-mesas {
        gap: 10px;
        padding: 8px 16px 12px;
      }
    }

    a.btn-mesa {
      margin: 0;
      min-width: unset !important;
      width: 100% !important;
      height: 0 !important;
      padding-bottom: 100% !important;
      padding-top: 0 !important;
      padding-left: 0 !important;
      padding-right: 0 !important;
      font-size: 0 !important;
      font-weight: 700;
      border-radius: 10px !important;
      position: relative;
      line-height: 1 !important;
      overflow: hidden;
      color: transparent !important;
      text-align: center;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
      transition: transform 0.15s ease, box-shadow 0.15s ease;
    }

    a.btn-mesa:active {
      transform: scale(0.96);
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    }

    a.btn-mesa::after {
      content: attr(data-numero);
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      font-size: 22px;
      font-weight: 700;
      color: #fff;
    }

    a.btn-mesa[data-cliente]::after {
      content: attr(data-numero);
      top: 28%;
      font-size: 18px;
    }

    a.btn-mesa[data-cliente]::before {
      content: attr(data-cliente);
      position: absolute;
      top: 55%;
      left: 50%;
      transform: translateX(-50%);
      font-size: 9px;
      font-weight: 500;
      color: rgba(255, 255, 255, 0.80);
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 90%;
      text-align: center;
      font-style: italic;
    }

    .btn-mesa .tempo-mesa {
      position: absolute;
      bottom: 5px;
      left: 50%;
      transform: translateX(-50%);
      font-size: 10px !important;
      font-weight: 600;
      color: rgba(255, 255, 255, 0.85);
      white-space: nowrap;
      line-height: 1;
      pointer-events: none;
      text-transform: lowercase;
      display: flex;
      align-items: center;
      gap: 1px;
    }

    .btn-mesa .tempo-mesa i {
      font-size: 10px !important;
    }

    a.btn-mesa[data-cliente] .tempo-mesa {
      bottom: 5px;
      font-size: 10px !important;
    }

    .filtros-wrapper {
      display: flex;
      gap: 8px;
      padding: 0 12px 10px;
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
      scrollbar-width: none;
    }

    .filtros-wrapper::-webkit-scrollbar {
      display: none;
    }

    .chip-filtro {
      flex-shrink: 0;
      white-space: nowrap;
    }

    .chip-filtro.ativo {
      background: #3f51b5 !important;
      color: #fff !important;
      border-color: #3f51b5 !important;
      box-shadow: 0 2px 8px rgba(63, 81, 181, 0.3) !important;
    }

    .chip-aberta.ativo {
      background: #3f51b5 !important;
      border-color: #3f51b5 !important;
      box-shadow: 0 2px 8px rgba(63, 81, 181, 0.3) !important;
    }

    .chip-pre-fechada.ativo {
      background: #d0a000 !important;
      border-color: #b08000 !important;
      color: #fff !important;
      box-shadow: 0 2px 8px rgba(208, 160, 0, 0.3) !important;
    }

    .chip-livre.ativo {
      background: #3f51b5 !important;
      border-color: #3f51b5 !important;
      color: #fff !important;
      box-shadow: 0 2px 8px rgba(63, 81, 181, 0.3) !important;
    }

    .secao-header {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 14px 16px 6px;
      font-weight: 700;
      font-size: 13px;
      text-transform: uppercase;
      letter-spacing: 0.5px;
    }

    .secao-header:not(:first-child) {
      margin-top: 6px;
      border-top: 1px solid #f0f0f0;
    }

    .secao-header .material-icons {
      font-size: 18px;
    }

    .secao-aberta {
      color: #e74c3c;
    }

    .secao-pre-fechada {
      color: #b08000;
    }

    .secao-livre {
      color: #27ae60;
    }

    .secao-count {
      background: rgba(0, 0, 0, 0.08);
      border-radius: 10px;
      padding: 1px 8px;
      font-size: 12px;
      margin-left: 2px;
    }

    .secao-vazia {
      grid-column: 1 / -1;
      padding: 4px 16px 12px;
      font-size: 13px;
      color: #bdbdbd;
      white-space: nowrap;
    }

    #btn-toggle-view {
      color: rgba(255, 255, 255, 0.9) !important;
    }

    /* ── Dark Theme Overrides ── */
    [data-theme="dark"] #modal-filtro-tempo>div {
      background: var(--bg-card) !important;
    }

    [data-theme="dark"] #modal-filtro-tempo>div>div:first-child {
      background: linear-gradient(135deg, #1a237e, #283593) !important;
    }

    [data-theme="dark"] .secao-header:not(:first-child) {
      border-top-color: var(--border-color);
    }

    [data-theme="dark"] .secao-count {
      background: rgba(255, 255, 255, 0.1);
    }

    [data-theme="dark"] .secao-vazia {
      color: var(--text-label);
    }

    [data-theme="dark"] #btn-filtro-tempo {
      background: var(--bg-card) !important;
      border-color: var(--color-primary) !important;
      color: var(--color-primary) !important;
    }
  </style>
</head>

<body>
  <script>
    loadPagina()
  </script>
  <div class="mdl-layout mdl-js-layout mdl-layout--fixed-header" id="page" style="display:none">
    <header class="mdl-layout__header">
      <div class="mdl-layout__header-row login">
        <span class="mdl-layout-title"><?= isset($_COOKIE['usuario']) ? htmlspecialchars($_COOKIE['usuario']) : '' ?></span>
        <div class="mdl-layout-spacer"></div>
        <button id="btn-toggle-view" class="mdl-button mdl-js-button mdl-button--icon" title="Alternar visualização">
          <i class="material-icons" id="icon-toggle-view">view_module</i>
        </button>
      </div>
    </header>

    <?php include 'includes/inc_menu.php'; ?>

    <main class="mdl-layout__content">
      <div style="padding: 10px 0 20px 0;">

        <!-- Search + Tempo filter -->
        <div class="pesquisa-wrapper" style="display:flex; align-items:center; gap:8px;">
          <div style="flex:1; position:relative;">
            <i class="material-icons pesquisa-icon">search</i>
            <input type="number" id="pesquisa" class="pesquisa-input" placeholder="Buscar mesa...">
          </div>
          <button id="btn-filtro-tempo" type="button" style="display:flex; align-items:center; gap:4px; padding:8px 14px; border-radius:20px; border:2px solid #3f51b5; background:#fff; color:#3f51b5; font-size:13px; font-weight:700; cursor:pointer; white-space:nowrap; box-shadow:0 1px 4px rgba(0,0,0,.1); transition:all .2s;">
            <i class="material-icons" style="font-size:18px;">schedule</i>
            <span id="btn-filtro-tempo-label">Tempo</span>
          </button>
        </div>

        <!-- Filter chips (lista view only) -->
        <div id="filtros-container" class="filtros-wrapper">
          <button class="mdl-button mdl-js-button btn-categoria chip-filtro ativo" data-filtro="todos">Todas</button>
          <button class="mdl-button mdl-js-button btn-categoria chip-filtro chip-aberta" data-filtro="aberta">Abertas</button>
          <button class="mdl-button mdl-js-button btn-categoria chip-filtro chip-pre-fechada" data-filtro="pre-fechada">Pré-Fechadas</button>
          <button class="mdl-button mdl-js-button btn-categoria chip-filtro chip-livre" data-filtro="livre">Livres</button>
        </div>

        <!-- Unified list view -->
        <div id="view-lista" class="box-mesas">
          <?php foreach ($mesaData as $m): ?>
            <a href="<?= $m['link'] ?>" data-venda="<?= $m['idVenda'] ?>" data-status="<?= $m['status'] ?>" data-numero="<?= $m['numero'] ?>" data-tempo-min="<?= $m['tempoMinutos'] ?>"
              <?= !empty($m['cliente']) ? 'data-cliente="' . htmlspecialchars(truncar($m['cliente'], 10)) . '"' : '' ?>
              class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored btn-mesa <?= $m['back'] ?>">
              <?= $m['numero'] ?>
              <?php if (!empty($m['tempo'])): ?><span class="tempo-mesa"><i class="material-icons">schedule</i><?= $m['tempo'] ?></span><?php endif; ?>
            </a>
          <?php endforeach; ?>
        </div>

        <!-- Sections view -->
        <div id="view-secoes" style="display:none">

          <!-- Abertas -->
          <div class="secao-header secao-aberta">
            <i class="material-icons">restaurant</i>
            <span>Abertas</span>
            <span class="secao-count" id="count-abertas">
              <?= count(array_filter($mesaData, function ($m) {
                return $m['status'] === 'aberta';
              })) ?>
            </span>
          </div>
          <div class="box-mesas" id="secao-abertas">
            <?php $abertas = array_filter($mesaData, function ($m) {
              return $m['status'] === 'aberta';
            }); ?>
            <?php if (empty($abertas)): ?>
              <p class="secao-vazia">Nenhuma mesa aberta</p>
              <?php else: foreach ($abertas as $m): ?>
                <a href="<?= $m['link'] ?>" data-venda="<?= $m['idVenda'] ?>" data-status="<?= $m['status'] ?>" data-numero="<?= $m['numero'] ?>" data-tempo-min="<?= $m['tempoMinutos'] ?>"
                  <?= !empty($m['cliente']) ? 'data-cliente="' . htmlspecialchars(truncar($m['cliente'], 10)) . '"' : '' ?>
                  class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored btn-mesa btn-red">
                  <?= $m['numero'] ?>
                  <?php if (!empty($m['tempo'])): ?><span class="tempo-mesa"><i class="material-icons">schedule</i><?= $m['tempo'] ?></span><?php endif; ?>
                </a>
            <?php endforeach;
            endif; ?>
          </div>

          <!-- Pré-Fechadas -->
          <div class="secao-header secao-pre-fechada">
            <i class="material-icons">schedule</i>
            <span>Pré-Fechadas</span>
            <span class="secao-count" id="count-pre-fechadas">
              <?= count(array_filter($mesaData, function ($m) {
                return $m['status'] === 'pre-fechada';
              })) ?>
            </span>
          </div>
          <div class="box-mesas" id="secao-pre-fechadas">
            <?php $preFechadas = array_filter($mesaData, function ($m) {
              return $m['status'] === 'pre-fechada';
            }); ?>
            <?php if (empty($preFechadas)): ?>
              <p class="secao-vazia">Nenhuma mesa pré-fechada</p>
              <?php else: foreach ($preFechadas as $m): ?>
                <a href="<?= $m['link'] ?>" data-venda="<?= $m['idVenda'] ?>" data-status="<?= $m['status'] ?>" data-numero="<?= $m['numero'] ?>" data-tempo-min="<?= $m['tempoMinutos'] ?>"
                  <?= !empty($m['cliente']) ? 'data-cliente="' . htmlspecialchars(truncar($m['cliente'], 10)) . '"' : '' ?>
                  class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored btn-mesa btn-yellow">
                  <?= $m['numero'] ?>
                  <?php if (!empty($m['tempo'])): ?><span class="tempo-mesa"><i class="material-icons">schedule</i><?= $m['tempo'] ?></span><?php endif; ?>
                </a>
            <?php endforeach;
            endif; ?>
          </div>

          <!-- Livres -->
          <div class="secao-header secao-livre">
            <i class="material-icons">check_circle</i>
            <span>Livres</span>
            <span class="secao-count" id="count-livres">
              <?= count(array_filter($mesaData, function ($m) {
                return $m['status'] === 'livre';
              })) ?>
            </span>
          </div>
          <div class="box-mesas" id="secao-livres">
            <?php $livres = array_filter($mesaData, function ($m) {
              return $m['status'] === 'livre';
            }); ?>
            <?php if (empty($livres)): ?>
              <p class="secao-vazia">Nenhuma mesa livre</p>
              <?php else: foreach ($livres as $m): ?>
                <a href="<?= $m['link'] ?>" data-venda="<?= $m['idVenda'] ?>" data-status="<?= $m['status'] ?>" data-numero="<?= $m['numero'] ?>"
                  class="mdl-button mdl-js-button mdl-button--raised mdl-button--colored btn-mesa">
                  <?= $m['numero'] ?>
                </a>
            <?php endforeach;
            endif; ?>
          </div>

        </div><!-- /view-secoes -->

      </div>
    </main>
  </div>

  <!-- Modal Filtro Tempo -->
  <div id="modal-filtro-tempo" style="display:none; position:fixed; inset:0; z-index:9999; background:rgba(0,0,0,.4); backdrop-filter:blur(4px); -webkit-backdrop-filter:blur(4px); align-items:center; justify-content:center;">
    <div style="background:#fff; border-radius:16px; width:90%; max-width:360px; box-shadow:0 8px 32px rgba(0,0,0,.25); overflow:hidden;">
      <div style="background:linear-gradient(135deg,#3f51b5,#5c6bc0); padding:18px 20px; display:flex; align-items:center; justify-content:space-between;">
        <div>
          <div style="display:flex; align-items:center; gap:8px; color:#fff; font-size:17px; font-weight:700;"><i class="material-icons" style="font-size:22px;">schedule</i> Filtro por Tempo</div>
          <div style="color:rgba(255,255,255,.8); font-size:12px; margin-top:4px;">Sem novos pedidos há mais de...</div>
        </div>
        <button id="modal-tempo-close" type="button" style="background:rgba(255,255,255,.15); border:none; cursor:pointer; padding:6px; border-radius:50%;"><i class="material-icons" style="color:#fff; font-size:20px;">close</i></button>
      </div>
      <div style="padding:20px; display:grid; grid-template-columns:1fr 1fr; gap:10px;">
        <button class="tempo-opt" data-tempo="0" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#e8eaf6; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">visibility</i> Todos</button>
        <button class="tempo-opt" data-tempo="10" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 10 min</button>
        <button class="tempo-opt" data-tempo="20" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 20 min</button>
        <button class="tempo-opt" data-tempo="30" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 30 min</button>
        <button class="tempo-opt" data-tempo="40" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 40 min</button>
        <button class="tempo-opt" data-tempo="50" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 50 min</button>
        <button class="tempo-opt" data-tempo="60" style="padding:14px 12px; border-radius:12px; border:2px solid #c5cae9; background:#f5f5ff; font-size:14px; font-weight:600; color:#3f51b5; cursor:pointer; transition:all .2s; grid-column:span 2; display:flex; align-items:center; justify-content:center; gap:6px;"><i class="material-icons" style="font-size:18px;">timer</i> 1 hora</button>
      </div>
    </div>
  </div>

  <?php include 'includes/inc_js.php'; ?>
  <?php include 'includes/inc_notifica_js.php'; ?>
  <script>
    function preloader() {
      ProcessingModal.hide();
      $('#page').show();
    }
    window.onload = preloader;

    if (localStorage.hasOwnProperty('carrinho')) {
      localStorage.removeItem('carrinho');
    }

    $(document).ready(function($) {

      // ── View toggle ──────────────────────────────────────────────
      var VIEW_KEY = 'mesas_view_mode';
      var currentView = localStorage.getItem(VIEW_KEY) || 'lista';

      function applyView(view) {
        if (view === 'secoes') {
          $('#view-lista').hide();
          $('#filtros-container').hide();
          $('#view-secoes').show();
          $('#icon-toggle-view').text('view_list');
        } else {
          $('#view-secoes').hide();
          $('#filtros-container').show();
          $('#view-lista').show();
          $('#icon-toggle-view').text('view_module');
        }
      }

      applyView(currentView);

      // ── Tempo filter (modal) ─────────────────────────────────────
      var tempoFiltroAtivo = 0;

      $('#btn-filtro-tempo').on('click', function() {
        $('#modal-filtro-tempo').css('display', 'flex');
      });
      $('#modal-tempo-close').on('click', function() {
        $('#modal-filtro-tempo').hide();
      });
      $('#modal-filtro-tempo').on('click', function(e) {
        if (e.target === this) $(this).hide();
      });

      $('.tempo-opt').on('click', function() {
        tempoFiltroAtivo = parseInt($(this).data('tempo')) || 0;
        $('.tempo-opt').css({
          border: '2px solid #c5cae9',
          background: '#f5f5ff',
          color: '#3f51b5'
        });
        $(this).css({
          border: '2px solid #3f51b5',
          background: '#e8eaf6',
          color: '#3f51b5'
        });
        if (tempoFiltroAtivo === 0) {
          $('#btn-filtro-tempo-label').text('Tempo');
          $('#btn-filtro-tempo').css({
            background: '#fff',
            color: '#3f51b5'
          });
        } else {
          var lbl = tempoFiltroAtivo >= 60 ? '> ' + Math.floor(tempoFiltroAtivo / 60) + 'h' : '> ' + tempoFiltroAtivo + 'min';
          $('#btn-filtro-tempo-label').text(lbl);
          $('#btn-filtro-tempo').css({
            background: '#3f51b5',
            color: '#fff'
          });
        }
        $('#modal-filtro-tempo').hide();
        var termo = $('#pesquisa').val() || '';
        if (currentView === 'lista') {
          var filtro = $('.chip-filtro.ativo').data('filtro');
          applyFilters(filtro, termo);
        } else {
          filterBySearch(termo);
        }
      });

      function applyFilters(filtro, termo) {
        var numStr = termo.toString();
        $('#view-lista .btn-mesa').each(function() {
          var status = $(this).data('status');
          var numero = $(this).data('numero').toString();
          var tMin = parseInt($(this).attr('data-tempo-min')) || 0;
          var matchF = (filtro === 'todos' || status === filtro);
          var matchS = (numStr === '' || numero.indexOf(numStr) !== -1);
          var matchT = (tempoFiltroAtivo === 0 || tMin >= tempoFiltroAtivo);
          $(this).toggle(matchF && matchS && matchT);
        });
      }

      $('#btn-toggle-view').on('click', function() {
        currentView = (currentView === 'lista') ? 'secoes' : 'lista';
        localStorage.setItem(VIEW_KEY, currentView);
        applyView(currentView);
        var termo = $('#pesquisa').val();
        if (termo) {
          filterBySearch(termo);
        }
      });

      // ── Filter chips ─────────────────────────────────────────────
      $(document).on('click', '.chip-filtro', function() {
        $('.chip-filtro').removeClass('ativo');
        $(this).addClass('ativo');
        var filtro = $(this).data('filtro');
        var termo = $('#pesquisa').val().toString();
        applyFilters(filtro, termo);
      });

      // ── Search ───────────────────────────────────────────────────
      function filterBySearch(termo) {
        var numStr = termo.toString();
        if (currentView === 'lista') {
          var filtro = $('.chip-filtro.ativo').data('filtro');
          applyFilters(filtro, numStr);
        } else {
          $('#view-secoes .btn-mesa').each(function() {
            var numero = $(this).data('numero').toString();
            var tMin = parseInt($(this).attr('data-tempo-min')) || 0;
            var matchS = (numStr === '' || numero.indexOf(numStr) !== -1);
            var matchT = (tempoFiltroAtivo === 0 || tMin >= tempoFiltroAtivo);
            $(this).toggle(matchS && matchT);
          });
          $('#count-abertas').text($('#secao-abertas .btn-mesa:visible').length);
          $('#count-pre-fechadas').text($('#secao-pre-fechadas .btn-mesa:visible').length);
          $('#count-livres').text($('#secao-livres .btn-mesa:visible').length);
        }
      }

      $('#pesquisa').on('input', function() {
        filterBySearch($(this).val());
      });

      // ── Reabrir mesa (btn-yellow) ─────────────────────────────────
      $(document).on('click', '.btn-yellow', function() {
        var venda = $(this).data('venda');
        var autorizado = '<?= (!empty($autorizacao) && isset($autorizacao->b_reabrir_mesa_comanda)) ? $autorizacao->b_reabrir_mesa_comanda : '' ?>';

        if (autorizado) {
          swal({
            title: 'Deseja reabrir a Mesa ?',
            type: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Sim, Reabrir !',
            cancelButtonText: 'Não Reabrir !',
            confirmButtonClass: 'btn btn-success',
            cancelButtonClass: 'btn',
            buttonsStyling: false,
            reverseButtons: true
          }).then((result) => {
            if (result.value) {
              $.ajax({
                url: 'ajax_reabrir_venda.php',
                type: 'POST',
                dataType: 'json',
                data: {
                  venda: venda
                },
                beforeSend: function() {
                  ProcessingModal.show({
                    text: 'Aguarde ...'
                  });
                },
                success: function(retorno) {
                  if (retorno.status == 1) {
                    location.reload();
                  } else {
                    ProcessingModal.hide();
                  }
                }
              });
            }
          });
        } else {
          swal('Alerta', 'Não é possível reabrir essa mesa !', 'warning');
        }
      });

    });
  </script>
</body>

</html>