<?php
require 'restringir.php'; // 🔒 Control de acceso
require 'conexion.php';
date_default_timezone_set('America/Argentina/Buenos_Aires');

// Obtener datos optimizados
function getData($con, $query) {
    $result = mysqli_query($con, $query);
    return mysqli_fetch_all($result, MYSQLI_ASSOC);
}

$salas = getData($con, "SELECT * FROM salas WHERE en_index = 1 ORDER BY id ASC");
$mesas = getData($con, "SELECT * FROM mesas WHERE en_index = 1 ORDER BY id ASC");
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>BAR SYSTEM | Gestión Premium</title>
  <link rel="icon" href="files/icon.png" type="image/png">
  
  <!-- CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
  
  <style>
    :root {
      --dark-1: #0a0a0f;
      --dark-2: #121218;
      --dark-3: #1a1a24;
      --accent: #3a86ff;
      --accent-hover: #2667cc;
      --text-light: #f8f9fa;
      --text-muted: #adb5bd;
      --success: #28a745;
      --danger: #dc3545;
      --warning: #ffc107;
      --border-radius: 6px;
      --transition: all 0.25s ease;
      --text-mutedd: #759464;
    }

    body {
      font-family: 'Inter', sans-serif;
      background-color: var(--dark-1);
      color: var(--text-light);
      margin: 0;
      padding: 0;
      min-height: 100vh;
    }

    /* Sidebar Elite */
    .sidebar {
      width: 280px;
      background: var(--dark-2);
      border-right: 1px solid rgba(255,255,255,0.05);
      height: 100vh;
      position: fixed;
      top: 0;
      left: 0;
      transition: var(--transition);
      z-index: 1000;
      display: flex;
      flex-direction: column;
    }

    .sidebar-header {
      padding: 20px;
      border-bottom: 1px solid rgba(255,255,255,0.05);
    }

    .sidebar-menu {
      background: var(--dark-2);

      flex: 1;
      overflow-y: auto;
      padding: 20px 0;
    }

    .sidebar-footer {
      padding: 20px;
      border-top: 1px solid rgba(255,255,255,0.05);
    }

    /* Main Content */
    .main-content {
      margin-left: 280px;
      padding: 30px;
      transition: var(--transition);
      min-height: 100vh;
    }

    /* Cards */
    .card-elite {
      background: black; 
      border: 1px solid rgba(255,255,255,0.05);
      border-radius: var(--border-radius);
      box-shadow: 0 4px 12px rgba(0,0,0,0.15);
      transition: var(--transition);
    }

    .card-elite:hover {
      transform: translateY(-3px);
      box-shadow: 0 6px 16px rgba(0,0,0,0.2);
      border-color: rgba(255,255,255,0.1);
    }

    .card-header-elite {
      background: var(--dark-3);
      border-bottom: 1px solid rgba(255,255,255,0.05);
      padding: 15px 20px;
      border-radius: var(--border-radius) var(--border-radius) 0 0;
    }

    /* Buttons */
    .btn-elite {
      border: none;
      border-radius: var(--border-radius);
      padding: 10px 20px;
      font-weight: 500;
      letter-spacing: 0.5px;
      transition: var(--transition);
    }

    .btn-primary-elite {
      background: var(--accent);
      color: white;
    }

    .btn-primary-elite:hover {
      background: var(--accent-hover);
      transform: translateY(-2px);
    }

    /* Tables Grid */
    .tables-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
      gap: 25px;
      padding: 20px 0;
    }

    .table-container {
      height: 700px;
      border-radius: var(--border-radius);
      overflow: hidden;
      box-shadow: 0 4px 12px rgba(0,0,0,0.1);
      transition: var(--transition);
    }

    .table-container:hover {
      box-shadow: 0 8px 24px rgba(0,0,0,0.2);
    }

    /* Status Indicators */
    .status-badge {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      margin-right: 8px;
    }

    .status-active {
      background: var(--success);
      box-shadow: 0 0 8px var(--success);
    }

    /* Utility Classes */
    .text-accent {
      color: var(--accent);
    }

    .bg-dark-2 {
      background: var(--dark-2);
    }

    .bg-dark-3 {
      background: var(--dark-3);
    }

    /* Responsive */
    @media (max-width: 992px) {
      .sidebar {
        transform: translateX(-100%);
      }
      .sidebar.active {
        transform: translateX(0);
      }
      .main-content {
        margin-left: 0;
      }
    }

    @media (max-width: 768px) {
      .tables-grid {
        grid-template-columns: 1fr;
      }
      .table-container {
        height: 600px;
      }
    }

    /* Animations */
    @keyframes fadeIn {
      from { opacity: 0; transform: translateY(10px); }
      to { opacity: 1; transform: translateY(0); }
    }

    .animate-fade {
      animation: fadeIn 0.3s ease-out forwards;
    }
  </style>
</head>
<body>
  <!-- Sidebar -->
  <div class="sidebar">
    <div class="sidebar-header">
      <h4 class="mb-0 text-accent">BAR </h4>
      <small class="text-muted">Gestión </small>
    </div>

    <div class="sidebar-menu">
      <div class="px-3 mb-4">
        


<div class="card-elite bg-dark-2 mb-3 border border-secondary shadow-sm">
  <div class="card-body">
    <h6 class="d-flex align-items-center mb-3 text-light">
      <span class="status-badge status-active"></span>
      Estado del Sistema
    </h6>
    <div class="d-flex justify-content-between mb-2">
      <span class="text-light">Mesas Ocupadas:</span>
      <strong id="contador-mesas" class="text-accent">0 / 5</strong>
    </div>
    <div class="d-flex justify-content-between">
      <span class="text-light">Turno:</span>
      <strong class="text-accent"><?= $turno ?></strong>
    </div>
  </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
  const TOTAL_MESAS = 5;
  let ocupadas = 0;
  const recibidas = new Set();

  window.addEventListener("message", function (event) {
    if (event.data && typeof event.data === 'object' && 'mesa' in event.data) {
      const mesaId = parseInt(event.data.mesa);
      const cantidad = parseInt(event.data.productos || 0);

      if (!recibidas.has(mesaId)) {
        recibidas.add(mesaId);
        if (cantidad > 0) ocupadas++;
        const texto = `${ocupadas} / ${TOTAL_MESAS}`;
        const el = document.getElementById("contador-mesas");
        if (el) el.textContent = texto;
      }
    }
  });

  // Pedir estado a cada iframe
  document.querySelectorAll("iframe[src^='mesa_']").forEach((iframe) => {
    iframe.addEventListener("load", () => {
      iframe.contentWindow.postMessage({ action: "verificar_productos" }, "*");
    });
  });
});
</script>
<div class="card-elite">
          <div class="card-header-elite">
            <h6 class="mb-0">Caja Diaria</h6>
          </div>
          <div class="card-body">
            <div class="d-flex justify-content-between mb-2">
              <span class="text-muteddx">Efectivo:</span>
              <strong id="efectivo-mesas">$0</strong>
            </div>
            <div class="d-flex justify-content-between mb-2">
              <span class="text-muteddy">Transferencias:</span>
              <strong id="transferencia-mesas">$0</strong>
            </div>
            <div class="d-flex justify-content-between">
              <span class="text-muteddz">Total:</span>
              <strong class="text-accent" id="total-mesas">$0</strong>
            <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="location.reload()">🔄</button>
</div>
</div>
          </div>
        </div>
      </div>

      <nav class="px-3">
        <h6 class="text-muted mb-3">NAVEGACIÓN</h6>
        <ul class="nav flex-column">
          <li class="nav-item">
            <a href="dashboard.php" target="_blank" rel="noopener noreferrer">
              <i class="bi bi-speedometer2 me-2"></i>
              Dashboard
            </a>
          </li>
          <li class="nav-item">
            <a href="tickets_para_bar.php" target="_blank" rel="noopener noreferrer">
              <i class="bi bi-cash-coin me-2"></i>
              Ver tickets
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link d-flex align-items-center" href="#">
              <i class="bi bi-people me-2"></i>
              Clientes
            </a>
          </li>
          <li class="nav-item">
            <a class="nav-link d-flex align-items-center" href="#">
              <i class="bi bi-clipboard-data me-2"></i>
              Reportes
            </a>
          </li>
        </ul>
      </nav>
    </div>

    <div class="sidebar-footer">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <div>
          <h6 class="mb-0"><?= $_SESSION['usuario'] ?? 'Usuario' ?></h6>
          <small class="text-muted"><?= $_SESSION['nivel'] ?? 'Admin' ?></small>
        </div>
        <img src="files/user.png" width="40" height="40" class="rounded-circle">
      </div>
  <a href="cerrar_sesion.php" class="btn btn-elite btn-primary-elite w-100">
  <i class="bi bi-box-arrow-right me-1"></i> Cerrar Sesión
</a>

    </div>
  </div>

  <!-- Main Content -->
  <div class="main-content">
    <div class="d-flex justify-content-between align-items-center mb-4">
      <div>
        <h4 class="mb-0">Control de Mesas</h4>
        
        <small class="text-muted">Gestión en tiempo real</small>
      </div>
      <div>
        <button id="btnMostrador" class="btn btn-primary">
          <i class="bi bi-plus-circle me-1"></i> Venta mostrador
        </button>

        </button>
        <button class="btn btn-elite bg-dark-3">
          <i class="bi bi-printer me-1"></i> Imprimir
        </button>
      </div>
    </div>

    
        <!-- Accordion: Mapa Mesas -->
        <div class="accordion mb-4" id="accordionMapaMesas">
          <div class="accordion-item bg-dark-3 border-0">
            <h2 class="accordion-header" id="headingMapa">
              <button class="accordion-button collapsed bg-dark-3 text-light" type="button" data-bs-toggle="collapse" data-bs-target="#collapseMapa" aria-expanded="false" aria-controls="collapseMapa">
                <i class="bi bi-map me-2"></i> Mapa Mesas
              </button>
            </h2>
            <div id="collapseMapa" class="accordion-collapse collapse" aria-labelledby="headingMapa" data-bs-parent="#accordionMapaMesas">
              <div class="accordion-body p-0">
                <iframe src="mapa_mesas.php?embed=1&ts=<?=time()?>" 
                        style="width:100%;height:1100px;border:0"></iframe>
              <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="location.reload()">Cerrar</button>
</div>
</div>
            </div>
          </div>
        </div>

<div class="tables-grid">
      <?php foreach ([1,2,3,4,5,6] as $id): ?>
        <div class="table-container animate-fade">
          <iframe src="mesa_<?= $id ?>.php"
                  loading="lazy"
                  title="Mesa <?= $id ?>"
                  class="w-100 h-100 border-0"></iframe>
        </div>
      <?php endforeach; ?>
    </div>
  </div>

  <!-- Payment Modal -->
  <div class="modal fade" id="paymentModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content bg-dark-2 border-0">
        <div class="modal-header border-bottom-0">
          <h5 class="modal-title">
            <i class="bi bi-credit-card me-2 text-accent"></i>
            Procesar Pago
          </h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <form id="paymentForm">
            <input type="hidden" id="paymentType">
            <input type="hidden" id="itemId">
            <input type="hidden" id="totalAmount">
            
            <div class="mb-4">
              <label class="form-label">Cliente</label>
              <input type="text" class="form-control bg-dark-3 border-0" id="clientName" required>
            </div>
            
            <div class="mb-4">
              <label class="form-label">Total a Cobrar</label>
              <input type="text" class="form-control bg-dark-3 border-0" id="displayTotal" disabled>
            </div>
            
            <div class="mb-4">
              <label class="form-label mb-3">Método de Pago</label>
              <div class="d-flex gap-2">
                <button type="button" class="btn btn-elite bg-dark-3 flex-grow-1 payment-method" data-method="cash">
                  <i class="bi bi-cash me-2"></i> Efectivo
                </button>
                <button type="button" class="btn btn-elite bg-dark-3 flex-grow-1 payment-method" data-method="transfer">
                  <i class="bi bi-bank me-2"></i> Transferencia
                </button>
              </div>
            </div>
            
            <div class="d-grid mt-4">
              <button type="submit" class="btn btn-elite btn-primary-elite py-3">
                <i class="bi bi-check-circle me-2"></i> Confirmar Pago
              </button>
            </div>
          </form>
        <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="location.reload()">Cerrar</button>
</div>
</div>
      </div>
    </div>
  </div>

  <!-- JavaScript -->
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  
  <script>
    // System Initialization
    $(document).ready(function() {
      // Update register totals
      function updateRegisterTotals() {
        $.getJSON("ajax/consultar_totales_mesas.php", function(data) {
          $('#efectivo-mesas').text("$" + data.efectivo.toFixed(2));
          $('#transferencia-mesas').text("$" + data.transferencia.toFixed(2));
          $('#total-mesas').text("$" + data.total.toFixed(2));
        }).fail(function() {
          console.error("Error al cargar los totales de caja");
        });
      }

      // Initialize and update every 10 seconds
      updateRegisterTotals();
      setInterval(updateRegisterTotals, 10000);

      // Payment method selection
      $('.payment-method').click(function() {
        $('.payment-method').removeClass('btn-primary-elite').addClass('bg-dark-3');
        $(this).removeClass('bg-dark-3').addClass('btn-primary-elite');
      });

      // Payment form submission
      $('#paymentForm').submit(function(e) {
        e.preventDefault();
        
        const paymentType = $('#paymentType').val();
        const itemId = $('#itemId').val();
        const total = parseFloat($('#totalAmount').val());
        const client = $('#clientName').val();
        const method = $('.payment-method.btn-primary-elite').data('method');
        
        // Process payment (AJAX call would go here)
        console.log('Processing payment:', {
          type: paymentType,
          id: itemId,
          total,
          client,
          method
        });
        
        // Close modal and refresh
        $('#paymentModal').modal('hide');
        updateRegisterTotals();
      });
    });

    // Function to open payment modal
    function openPaymentModal(type, id, total, client = '') {
      $('#paymentType').val(type);
      $('#itemId').val(id);
      $('#totalAmount').val(total);
      $('#clientName').val(client);
      $('#displayTotal').val('$' + parseFloat(total).toFixed(2));
      $('.payment-method').removeClass('btn-primary-elite').addClass('bg-dark-3');
      $('.payment-method[data-method="cash"]').removeClass('bg-dark-3').addClass('btn-primary-elite');
      
      const modal = new bootstrap.Modal(document.getElementById('paymentModal'));
      modal.show();
    }

    // Mobile sidebar toggle
    function toggleSidebar() {
      $('.sidebar').toggleClass('active');
    }
  </script>
  <!-- Modal Venta Mostrador -->
<div class="modal fade" id="modalMostrador" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <div class="modal-content border-0">
      <div class="modal-body p-0">
        <!-- Iframe con la mesa 999 -->
        <iframe id="iframeMostrador" src="mostrador.php?embed=1"
                style="width:100%;height:650px;border:0"></iframe>
      <div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" onclick="location.reload()">Cerrar</button>
</div>
</div>
    </div>
  </div>
</div>
<script>
document.getElementById('btnMostrador').addEventListener('click',()=>{
  new bootstrap.Modal(document.getElementById('modalMostrador')).show();
});
</script>
<script>
  window.addEventListener('message', function(event) {
    if (event.data && event.data.action === 'modal_closed') {
      location.reload(); // 94 Recargar bar.php completo
    }
  });
</script>
</body>
</html>