<?php
require 'restringir.php'; // 🔒 protección
require 'conexion.php';
date_default_timezone_set('America/Argentina/Buenos_Aires');

// --- Salas activas ---
$salas = mysqli_fetch_all(mysqli_query($con, "SELECT * FROM salas WHERE en_index = 1 ORDER BY id ASC"), MYSQLI_ASSOC);
$productos = mysqli_fetch_all(mysqli_query($con, "SELECT * FROM productos ORDER BY nombre ASC"), MYSQLI_ASSOC);
$alquileres = mysqli_fetch_all(mysqli_query($con, "SELECT * FROM alquileres ORDER BY nombre ASC"), MYSQLI_ASSOC);

// --- Mesas activas ---
$mesas = mysqli_fetch_all(mysqli_query($con, "SELECT * FROM mesas WHERE en_index = 1 ORDER BY id ASC"), MYSQLI_ASSOC);
$productos_mesas = mysqli_fetch_all(mysqli_query($con, "SELECT * FROM productos_mesas WHERE visible = 1 ORDER BY nombre ASC"), MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Sala Turnos</title>
  <link rel="icon" href="files/icon.png" type="image/png">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
  <link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@400;500;700&family=Share+Tech+Mono&display=swap" rel="stylesheet">
  <style>
    :root {
      --dark-bg: #0f0f1a;
      --darker-bg: #080810;
      --panel-bg: rgba(15, 15, 30, 0.8);
      --neon-blue: #00f0ff;
      --neon-pink: #ff00f0;
      --neon-purple: #b300ff;
      --text-primary: #e0e0ff;
      --text-secondary: #a0a0c0;
      --panel-glow: rgba(0, 240, 255, 0.2);
      --danger-red: #ff3864;
      --success-green: #00ffa3;
      --warning-orange: #ff9e00;
      --scanline: rgba(0, 240, 255, 0.03);
    }

    body {
      font-family: 'Share Tech Mono', monospace;
      background-color: var(--dark-bg);
      background-image: 
        linear-gradient(var(--scanline) 1px, transparent 1px),
        linear-gradient(90deg, var(--scanline) 1px, transparent 1px);
      background-size: 20px 20px;
      color: var(--text-primary);
      margin: 0;
      padding: 0;
      overflow-x: hidden;
      letter-spacing: 0.5px;
    }

    /* CRT screen effect */
    body::before {
      content: "";
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(
        rgba(18, 16, 16, 0) 50%, 
        rgba(0, 0, 0, 0.25) 50%
      );
      background-size: 100% 4px;
      pointer-events: none;
      z-index: 1000;
    }

    /* VHS distortion effect */
    body::after {
      content: "";
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: 
        linear-gradient(0deg, rgba(0, 240, 255, 0.03) 0%, transparent 100%),
        linear-gradient(90deg, rgba(255, 0, 240, 0.03) 0%, transparent 100%);
      pointer-events: none;
      z-index: 1000;
      animation: vhs-flicker 0.1s infinite;
    }

    @keyframes vhs-flicker {
      0% { opacity: 0.9; }
      50% { opacity: 1; }
      100% { opacity: 0.8; }
    }

    /* Typography */
    h1, h2, h3, h4, h5, h6 {
      font-family: 'Orbitron', sans-serif;
      font-weight: 700;
      text-transform: uppercase;
      letter-spacing: 2px;
      color: var(--neon-blue);
      text-shadow: 0 0 10px var(--panel-glow);
    }

    /* Main layout */
    #caja-panel {
      position: fixed;
      left: 0;
      top: 0;
      height: 100vh;
      width: 280px;
      background: var(--panel-bg);
      border-right: 1px solid var(--neon-blue);
      padding: 25px;
      z-index: 10000;
      box-shadow: 0 0 30px var(--panel-glow);
      transition: all 0.4s cubic-bezier(0.68, -0.55, 0.27, 1.55);
      overflow-y: auto;
      backdrop-filter: blur(5px);
    }

    #toggle-caja {
  left: 100%;
  margin-left: 5px;
  position: absolute;

      position: absolute;
      top: 20px;
      right: -45px;
      background: var(--neon-blue);
      color: var(--dark-bg);
      border-radius: 50%;
      width: 40px;
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      box-shadow: 0 0 15px var(--panel-glow);
      font-size: 18px;
      transition: all 0.3s ease;
      border: none;
      z-index: 10001;
    }

    #toggle-caja:hover {
      transform: scale(1.1) rotate(90deg);
      box-shadow: 0 0 25px var(--neon-pink);
      background: var(--neon-pink);
    }

    #main-content {
      margin-left: 280px;
      padding: 30px;
      transition: all 0.4s ease;
      background: transparent;
    }

    /* Futuristic Cards */
    .card {
      background: var(--panel-bg);
      border: 1px solid var(--neon-blue);
      border-radius: 0;
      margin-bottom: 25px;
      box-shadow: 0 5px 25px rgba(0, 0, 0, 0.5);
      transition: all 0.3s ease;
      backdrop-filter: blur(5px);
      overflow: hidden;
      position: relative;
    }

    .card::before {
      content: '';
      position: absolute;
      top: -2px;
      left: -2px;
      right: -2px;
      bottom: -2px;
      background: linear-gradient(45deg, var(--neon-blue), var(--neon-pink));
      z-index: -1;
      opacity: 0.3;
      transition: opacity 0.3s ease;
    }

    .card:hover {
      transform: translateY(-5px);
      box-shadow: 0 10px 35px rgba(0, 240, 255, 0.3);
      border-color: var(--neon-pink);
    }

    .card:hover::before {
      opacity: 0.6;
    }

    .card h5 {
      color: var(--neon-blue);
      font-size: 1.2rem;
      padding-bottom: 12px;
      margin-bottom: 15px;
      border-bottom: 1px solid rgba(0, 240, 255, 0.3);
      position: relative;
    }

    .card h5::after {
      content: '';
      position: absolute;
      bottom: -1px;
      left: 0;
      width: 50px;
      height: 2px;
      background: var(--neon-blue);
    }

    /* Form Elements */
    .form-control, .form-select {
      background: rgba(10, 10, 20, 0.8);
      border: 1px solid var(--neon-blue);
      color: var(--text-primary);
      border-radius: 0;
      padding: 10px 15px;
      transition: all 0.3s ease;
      font-family: 'Share Tech Mono', monospace;
    }

    .form-control:focus, .form-select:focus {
      background: rgba(15, 15, 30, 0.9);
      border-color: var(--neon-pink);
      box-shadow: 0 0 0 0.25rem rgba(0, 240, 255, 0.25);
      color: white;
    }

    /* Buttons */
    .btn {
      border-radius: 0;
      font-weight: 500;
      padding: 8px 16px;
      transition: all 0.3s ease;
      font-family: 'Orbitron', sans-serif;
      letter-spacing: 1px;
      border: none;
      text-transform: uppercase;
      font-size: 0.8rem;
      position: relative;
      overflow: hidden;
    }

    .btn::after {
      content: '';
      position: absolute;
      top: -50%;
      left: -60%;
      width: 200%;
      height: 200%;
      background: linear-gradient(
        to bottom right, 
        rgba(255, 255, 255, 0.3), 
        rgba(255, 255, 255, 0)
      );
      transform: rotate(30deg);
      transition: all 0.3s;
    }

    .btn:hover::after {
      left: 100%;
    }

    .btn-success {
      background: linear-gradient(135deg, var(--success-green), #00C782);
      color: var(--dark-bg);
    }

    .btn-success:hover {
      background: linear-gradient(135deg, #00E693, #00B372);
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(0, 255, 163, 0.3);
    }

    .btn-danger {
      background: linear-gradient(135deg, var(--danger-red), #D1003F);
      color: white;
    }

    .btn-danger:hover {
      background: linear-gradient(135deg, #FF4D7A, #E10045);
      transform: translateY(-2px);
      box-shadow: 0 5px 15px rgba(255, 0, 117, 0.3);
    }

    .btn-sm {
      padding: 5px 10px;
      font-size: 0.7rem;
    }

    /* Ticket Box */
    .ticket-box {
      background: rgba(10, 10, 20, 0.8);
      padding: 15px;
      border-left: 4px solid var(--neon-blue);
      font-size: 0.9rem;
      font-family: 'Share Tech Mono', monospace;
      box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.5);
      border-radius: 0;
    }

    .ticket-box div {
      margin-bottom: 5px;
      display: flex;
      justify-content: space-between;
    }

    .ticket-box div:last-child {
      font-weight: bold;
      color: var(--neon-blue);
      margin-top: 10px;
      padding-top: 8px;
      border-top: 1px dashed rgba(0, 240, 255, 0.3);
    }

    /* List Items */
    .list-group-item {
      background: rgba(20, 20, 40, 0.8);
      border: 1px solid rgba(0, 240, 255, 0.1);
      color: var(--text-primary);
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 12px;
      margin-bottom: 5px;
      transition: all 0.3s ease;
      font-family: 'Share Tech Mono', monospace;
      border-radius: 0;
    }

    .list-group-item:hover {
      background: rgba(30, 30, 60, 0.9);
      border-color: rgba(0, 240, 255, 0.3);
    }

    .btn-remove {
      background: transparent;
      border: none;
      color: var(--danger-red);
      padding: 2px 5px;
      font-size: 1rem;
      transition: all 0.2s ease;
      cursor: pointer;
    }

    .btn-remove:hover {
      transform: scale(1.2);
      color: #FF00A8;
    }

    /* Duration Controls */
    .modificar-duracion {
      width: 42px;
      height: 42px;
      border-radius: 0 !important;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      font-weight: bold;
      box-shadow: 0 3px 10px rgba(0, 0, 0, 0.5);
    }

    .duracion-texto {
      font-weight: bold;
      font-size: 1.1rem;
      color: var(--neon-blue);
      display: inline-block;
      min-width: 60px;
      text-align: center;
      font-family: 'Share Tech Mono', monospace;
      text-shadow: 0 0 5px rgba(0, 240, 255, 0.5);
    }

    /* Caja Panel Styling */
    #caja-panel h6 {
      color: var(--neon-blue);
      font-size: 1rem;
      margin-bottom: 15px;
      text-transform: uppercase;
      letter-spacing: 1px;
      position: relative;
      padding-bottom: 8px;
    }

    #caja-panel h6::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 0;
      width: 40px;
      height: 2px;
      background: var(--neon-blue);
    }

    #caja-panel p {
      margin-bottom: 8px;
      font-family: 'Share Tech Mono', monospace;
      display: flex;
      justify-content: space-between;
    }

    #caja-panel strong {
      color: var(--text-primary);
      font-weight: normal;
    }

    #caja-panel hr {
      border-color: rgba(0, 240, 255, 0.2);
      margin: 15px 0;
    }

    /* Badges */
    .badge {
      font-weight: 500;
      padding: 5px 10px;
      border-radius: 0;
      font-family: 'Share Tech Mono', monospace;
      font-size: 0.75rem;
      background: var(--neon-purple);
      color: var(--dark-bg);
    }

    /* Responsive Design */
    @media (max-width: 992px) {
      #caja-panel {
        width: 240px;
        padding: 20px;
      }
      
      #main-content {
        margin-left: 240px;
        padding: 20px;
      }
    }

    @media (max-width: 768px) {
      #caja-panel {
        transform: translateX(-100%);
      }
      
      #caja-panel.active {
        transform: translateX(0);
      }
      
      #main-content {
        margin-left: 0;
      }
      
      #toggle-caja {
  left: 100%;
  margin-left: 5px;
  position: absolute;

        right: -50px;
      }
    }

    /* Animations */
    @keyframes pulse {
      0% { opacity: 0.6; }
      50% { opacity: 1; }
      100% { opacity: 0.6; }
    }

    .pulse {
      animation: pulse 2s infinite ease-in-out;
    }

    @keyframes float {
      0% { transform: translateY(0px); }
      50% { transform: translateY(-5px); }
      100% { transform: translateY(0px); }
    }

    .float {
      animation: float 3s infinite ease-in-out;
    }

    /* IFrames */
    .salas-iframes {
      display: flex;
      flex-wrap: nowrap;
      gap: 25px;
      overflow-x: auto;
      margin: 25px 0;
      padding: 10px 0;
      scrollbar-color: var(--neon-blue) var(--dark-bg);
  padding-left: 30px;
    }

    .iframe-sala {
      width: 250px;
      min-width: 250px;
      border: none;
      box-shadow: 0 0 20px rgba(0, 240, 255, 0.2);
      transition: all 0.3s ease;
      height: 900px;
    }

    .iframe-sala:hover {
      transform: scale(1.02);
      box-shadow: 0 0 30px var(--neon-pink);
    }

    /* Modal Enhancements */
    .modal-content {
      background: var(--panel-bg);
      border: 1px solid var(--neon-blue);
      border-radius: 0;
      color: var(--text-primary);
      box-shadow: 0 0 30px var(--panel-glow);
    }

    .modal-header {
      border-bottom: 1px solid rgba(0, 240, 255, 0.2);
    }

    .modal-footer {
      border-top: 1px solid rgba(0, 240, 255, 0.2);
    }

    .close {
      color: var(--text-primary);
      text-shadow: none;
      opacity: 0.7;
    }

    .close:hover {
      color: var(--neon-pink);
      opacity: 1;
    }

    /* Caja Totals */
    .caja-total {
      font-size: 1.2rem;
      color: var(--neon-blue);
      text-shadow: 0 0 5px rgba(0, 240, 255, 0.5);
      margin-top: 10px;
      padding-top: 10px;
      border-top: 1px solid rgba(0, 240, 255, 0.3);
    }

    /* Loading Animation */
    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    .loading-spinner {
      display: inline-block;
      width: 20px;
      height: 20px;
      border: 3px solid rgba(0, 240, 255, 0.3);
      border-radius: 50%;
      border-top-color: var(--neon-blue);
      animation: spin 1s ease-in-out infinite;
      margin-right: 10px;
      vertical-align: middle;
    }

    /* Grid Layout for Salas */
    @media (min-width: 1200px) {
      .sala-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
        gap: 25px;
      }
    }

    /* Retro computer terminal effect */
    .terminal-effect {
      position: relative;
    }

    .terminal-effect::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(
        to bottom,
        rgba(0, 240, 255, 0.1) 0%,
        transparent 10%
      );
      background-size: 100% 5px;
      pointer-events: none;
      z-index: 1;
    }

    /* Glitch effect */
    .glitch {
      position: relative;
    }

    .glitch::before, .glitch::after {
      content: attr(data-text);
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      opacity: 0.8;
    }

    .glitch::before {
      color: var(--neon-pink);
      z-index: -1;
      animation: glitch-effect 3s infinite;
    }

    .glitch::after {
      color: var(--neon-blue);
      z-index: -2;
      animation: glitch-effect 2s infinite reverse;
    }

    @keyframes glitch-effect {
      0% { transform: translate(0); }
      20% { transform: translate(-3px, 3px); }
      40% { transform: translate(-3px, -3px); }
      60% { transform: translate(3px, 3px); }
      80% { transform: translate(3px, -3px); }
      100% { transform: translate(0); }
    }

    /* Matrix rain effect for caja panel */
    #caja-panel {
      position: relative;
      overflow: hidden;
    }

    #caja-panel::before {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(
        to bottom,
        transparent 0%,
        rgba(0, 240, 255, 0.05) 50%,
        transparent 100%
      );
      animation: matrix-rain 20s linear infinite;
      pointer-events: none;
    }

    @keyframes matrix-rain {
      from { background-position: 0 0; }
      to { background-position: 0 100%; }
    }

    /* Neon border animation */
    .neon-border {
      position: relative;
    }

    .neon-border::before {
      content: '';
      position: absolute;
      top: -2px;
      left: -2px;
      right: -2px;
      bottom: -2px;
      z-index: -1;
      background: linear-gradient(45deg, 
        var(--neon-blue), var(--neon-pink), var(--neon-purple), var(--neon-blue));
      background-size: 400%;
      animation: neon-border-animation 8s linear infinite;
      opacity: 0;
      transition: opacity 0.3s;
    }

    .neon-border:hover::before {
      opacity: 1;
    }

    @keyframes neon-border-animation {
      0% { background-position: 0 0; }
      100% { background-position: 400% 0; }
    }

    /* Retro VHS tracking lines */
    .vhs-lines {
      position: relative;
    }

    .vhs-lines::after {
      content: '';
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: repeating-linear-gradient(
        to bottom,
        transparent,
        transparent 3px,
        rgba(0, 240, 255, 0.1) 3px,
        rgba(0, 240, 255, 0.1) 6px
      );
      pointer-events: none;
      z-index: 1;
    }

    /* Responsive iframes */
    @media (max-width: 768px) {
      .iframe-sala {
        width: 300px;
        min-width: 300px;
        height: 600px;
      }
    }
  
#toggle-caja {
  left: 100%;
  margin-left: 5px;
  position: absolute;

  position: absolute;
  top: 10px;
  right: -30px;
  background-color: #00bcd4;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 5px 8px;
  cursor: pointer;
  z-index: 999;
}
</style>

</head>
<body class="terminal-effect vhs-lines">

<div style="display: flex;">
  <div id="caja-panel" class="neon-border">
  <button id="toggle-caja" title="Ocultar caja"><span id="toggle-caja-icon">◄</span></button>
    <div id="toggle-caja">◄</div>
    <h6 class="glitch" data-text="CAJA">CAJA</h6>
    <div class="mb-3">
      <p>Efectivo: <strong id="total-efectivo" class="pulse">$0.00</strong></p>
      <p>Transferencia: <strong id="total-transferencia" class="pulse">$0.00</strong></p>
    </div>
    <hr>
    <div class="caja-total">
      <p>Total: <strong id="total-general" class="float">$0.00</strong></p>
    </div>
    <hr>
    <div class="time-display">
      <p id="current-time">--:-- --</p>
      <p id="current-date">--- --, ----</p>
    </div>
    <?php if (isset($_SESSION['usuario'])): ?>
  <div style="font-size: 0.8rem; background: rgba(255,255,255,0.05); padding: 8px; border-radius: 6px; margin-bottom: 10px;">
    🔓 Logueado como: <strong><?= $_SESSION['usuario'] ?></strong><br>
    Rol: <span style="text-transform: uppercase;"><?= $_SESSION['nivel'] ?></span><br>
    <a href="index.php" class="btn btn-sm btn-outline-light mt-2">Cerrar sesión</a>
  </div>
<?php endif; ?>
  </div>

  <div class="salas-iframes">
    <iframe src="https://nodo25.netfan.host/humclubdemusica/sala_1.php" class="iframe-sala"></iframe>
    <iframe src="https://nodo25.netfan.host/humclubdemusica/sala_2.php" class="iframe-sala"></iframe>
    <iframe src="https://nodo25.netfan.host/humclubdemusica/sala_h.php" class="iframe-sala"></iframe>
    <iframe src="https://nodo25.netfan.host/humclubdemusica/sala_m.php" class="iframe-sala"></iframe>
    <iframe src="https://nodo25.netfan.host/humclubdemusica/sala_bandas.php" class="iframe-sala"></iframe>
  </div>
</div>




<!-- Modal único para cobro de salas -->
<div class="modal fade" id="modalCobroSala" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content neon-border">
      <form id="formCobroSala" class="p-3">
        <h5 class="mb-3 glitch" data-text="CERRAR SALA">💰 CERRAR SALA</h5>
        <input type="hidden" id="modal-sala-id" name="sala_id">
        <input type="hidden" id="modal-total" name="total">

        <div class="mb-2">
          <label>Cliente</label>
          <input type="text" class="form-control" id="modal-cliente" name="cliente">
        </div>

        <div class="mb-2">
          <label>Comentario</label>
          <textarea class="form-control" id="modal-comentario" name="comentario" rows="2"></textarea>
        </div>

        <div class="mb-3">
          <div class="ticket-box">
            Total a cobrar: $<span id="texto-total">0.00</span>
          </div>
        </div>

        <div class="mb-3">
          <label class="d-block"><input type="radio" name="forma_pago" value="efectivo" checked> EFECTIVO</label>
          <label class="d-block"><input type="radio" name="forma_pago" value="transferencia"> TRANSFERENCIA</label>
          <label class="d-block"><input type="radio" name="forma_pago" value="dividido"> DIVIDIDO</label>
        </div>

        <div id="dividido-inputs" class="mb-3" style="display:none;">
          <input type="number" class="form-control mb-2" id="input-efectivo" placeholder="MONTO EN EFECTIVO">
          <input type="number" class="form-control" id="input-transferencia" placeholder="MONTO EN TRANSFERENCIA">
        </div>

        <div class="alert alert-danger d-none" id="alerta-monto">⚠️ EL MONTO NO COINCIDE CON EL TOTAL</div>

        <div class="mt-3 text-end">
          <button type="submit" class="btn btn-primary">CONFIRMAR COBRO</button>
        </div>
      </form>
    </div>
  </div>
</div>

<!-- Modal para cobrar mesa -->
<div class="modal fade" id="modalCobroMesa" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content neon-border">
      <form id="formCobroMesa" class="p-3">
        <h5 class="mb-3 glitch" data-text="CERRAR MESA">💰 CERRAR MESA</h5>
        <input type="hidden" id="mesa-id" name="mesa_id">
        <input type="hidden" id="mesa-total" name="monto">

        <div class="mb-2">
          <label>Cliente</label>
          <input type="text" class="form-control" id="mesa-cliente" name="cliente">
        </div>

        <div class="mb-2">
          <label>Comentario</label>
          <textarea class="form-control" id="mesa-comentario" name="comentario" rows="2"></textarea>
        </div>

        <div class="mb-2">
          <label>Total</label>
          <input type="text" class="form-control" id="mesa-total-visible" disabled>
        </div>

        <div class="mb-2">
          <label>Forma de pago</label>
          <select class="form-select" id="mesa-forma-pago" name="forma_pago" required>
            <option value="">SELECCIONAR</option>
            <option value="efectivo">EFECTIVO</option>
            <option value="transferencia">TRANSFERENCIA</option>
            <option value="dividido">DIVIDIDO</option>
          </select>
        </div>

        <div class="row mb-2" id="mesa-dividido" style="display: none;">
          <div class="col">
            <label>Efectivo</label>
            <input type="number" step="0.01" class="form-control" id="mesa-efectivo" name="efectivo">
          </div>
          <div class="col">
            <label>Transferencia</label>
            <input type="number" step="0.01" class="form-control" id="mesa-transferencia" name="transferencia">
          </div>
        </div>

        <div class="d-flex justify-content-between mt-3">
          <button type="submit" class="btn btn-success">💾 CONFIRMAR COBRO</button>
          <a id="mesa-ver-ticket" href="#" target="_blank" class="btn btn-outline-primary d-none">VER TICKET</a>
        </div>
      </form>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Función para actualizar el ticket de la sala
function actualizarTicket(salaId) {
  const form = $('#form_sala_' + salaId);
  const hora = form.find('.hora-inicio').val();
  const duracionMin = parseInt(form.find('input[name="duracion"]').val()) || 0;
  const descuento = parseInt(form.find('.descuento-input').val()) || 0;

  $.post('ajax/ajax_precio_sala.php', { sala_id: salaId, hora: hora }, function(data) {
    let base = parseFloat(data.precio) * (duracionMin / 60);
    let totalProd = 0;
    form.find('.lista-productos li').each(function() {
      totalProd += parseFloat($(this).data('precio'));
    });
    let totalAlq = 0;
    form.find('.lista-alquileres li').each(function() {
      totalAlq += parseFloat($(this).data('precio'));
    });

    let subtotal = base + totalProd + totalAlq;
    let totalFinal = subtotal - (subtotal * descuento / 100);
    $('#ticket_' + salaId).html(`
      <div class="text-center mb-2">📋 TICKET</div>
      <div>Sala: <span>$${base.toFixed(2)}</span></div>
      <div>Productos: <span>$${totalProd.toFixed(2)}</span></div>
      <div>Alquileres: <span>$${totalAlq.toFixed(2)}</span></div>
      <div>Descuento: <span>${descuento}%</span></div>
      <div class="mt-2">Total: <span>$${totalFinal.toFixed(2)}</span></div>
    `);
    form.find('.cobrar-btn').attr('data-total', totalFinal.toFixed(2));
  }, 'json');
}

// Función para actualizar el ticket de la mesa
function actualizarTicketMesa(mesaId) {
  let total = 0;
  $('#productos_mesa_' + mesaId + ' li').each(function() {
    total += parseFloat($(this).data('precio'));
  });
  $('#ticket_mesa_' + mesaId).html(`
    <div class="text-center mb-2">📋 TICKET</div>
    <div>Hora: <span class="ticket-hora">${$('#form_mesa_' + mesaId + ' .hora-mesa').val()}</span></div>
    <div>Productos: <span>$${total.toFixed(2)}</span></div>
    <div class="mt-2">Total: <span>$${total.toFixed(2)}</span></div>
  `);
}

// Eventos para salas
$(document).on('change', '.hora-inicio, .descuento-input', function() {
  const sala = $(this).closest('form').attr('id').split('_')[2];
  actualizarTicket(sala);
});

$(document).on('click', '.modificar-duracion', function() {
  const sala = $(this).data('sala');
  let campo = $('#form_sala_' + sala + ' input[name="duracion"]');
  let actual = parseInt(campo.val()) || 0;
  let nuevo = actual + parseInt($(this).data('minutos'));
  if (nuevo < 0) nuevo = 0;
  campo.val(nuevo);
  $('#duracion_' + sala).text((nuevo / 60).toFixed(2) + 'h');
  actualizarTicket(sala);
});

$(document).on('change', '.producto-select', function() {
  const sala = $(this).data('sala');
  const val = $(this).find('option:selected');
  const precio = parseFloat(val.data('precio'));
  $('#productos_' + sala).append(`
    <li class="list-group-item" data-precio="${precio}">
      ${val.text()} 
      <button type="button" class="btn btn-sm btn-outline-danger btn-remove">🗑</button>
    </li>
  `);
  $(this).val('');
  actualizarTicket(sala);
});

$(document).on('change', '.alquiler-select', function() {
  const sala = $(this).data('sala');
  const val = $(this).find('option:selected');
  const precio = parseFloat(val.data('precio'));
  $('#alquileres_' + sala).append(`
    <li class="list-group-item" data-precio="${precio}">
      ${val.text()} 
      <button type="button" class="btn btn-sm btn-outline-danger btn-remove">🗑</button>
    </li>
  `);
  $(this).val('');
  actualizarTicket(sala);
});

// Eventos para mesas
$(document).on('change', '.hora-mesa', function() {
  const mesaId = $(this).data('mesa');
  const hora = $(this).val();
  $('#ticket_mesa_' + mesaId + ' .ticket-hora').text(hora);
});

$(document).on('change', '.producto-mesa-select', function() {
  const mesa = $(this).data('mesa');
  const val = $(this).find('option:selected');
  const precio = parseFloat(val.data('precio'));
  const stock = val.data('stock');
  const info = stock !== '' && stock !== null ? `Stock: ${stock}` : 'Consumo libre';
  $('#productos_mesa_' + mesa).append(`
    <li class="list-group-item d-flex justify-content-between align-items-center"
        data-precio="${precio}"
        data-nombre="${val.text()}">
      <span class="nombre-prod">${val.text()}</span>
      <span class="badge">${info}</span>
      <button type="button" class="btn btn-sm btn-outline-danger btn-remove">🗑</button>
    </li>
  `);
  $(this).val('');
  actualizarTicketMesa(mesa);
});

// Evento para eliminar productos/alquileres
$(document).on('click', '.btn-remove', function() {
  $(this).closest('li').remove();
  const id = $(this).closest('form').attr('id');
  if (id.includes('mesa')) {
    actualizarTicketMesa(id.split('_')[2]);
  } else {
    actualizarTicket(id.split('_')[2]);
  }
});

// Panel de caja
document.addEventListener("DOMContentLoaded", function() {
  // Actualizar hora y fecha
  function updateDateTime() {
    const now = new Date();
    const timeStr = now.toLocaleTimeString('es-AR', { hour: '2-digit', minute: '2-digit' });
    const dateStr = now.toLocaleDateString('es-AR', { weekday: 'long', day: 'numeric', month: 'long' }).toUpperCase();
    document.getElementById('current-time').textContent = timeStr;
    document.getElementById('current-date').textContent = dateStr;
  }
  updateDateTime();
  setInterval(updateDateTime, 60000);

  function actualizarCaja() {
    fetch("ajax/consultar_totales_caja.php")
      .then(r => r.json())
      .then(data => {
        document.getElementById('total-efectivo').innerText = "$" + data.efectivo;
        document.getElementById('total-transferencia').innerText = "$" + data.transferencia;
        document.getElementById('total-general').innerText = "$" + data.total;
      });
  }

  actualizarCaja();
  setInterval(actualizarCaja, 10000);

  // Toggle caja panel
  document.getElementById('toggle-caja').addEventListener('click', function() {
    const panel = document.getElementById('caja-panel');
    if (panel.style.left === "0px") {
      panel.style.left = "-280px";
      document.getElementById('main-content').style.marginLeft = "0";
      this.innerHTML = "►";
    } else {
      panel.style.left = "0px";
      document.getElementById('main-content').style.marginLeft = "280px";
      this.innerHTML = "◄";
    }
  });
});

// Script para manejar el modal de cobro de salas
document.addEventListener("DOMContentLoaded", () => {
  const modalEl = document.getElementById('modalCobroSala');
  const bsModal = new bootstrap.Modal(modalEl);
  const formCobro = document.getElementById('formCobroSala');
  const txtTotal = document.getElementById('texto-total');
  const inpSalaId = document.getElementById('modal-sala-id');
  const inpTotal = document.getElementById('modal-total');
  const inpCliente = document.getElementById('modal-cliente');
  const inpComentario = document.getElementById('modal-comentario');
  const divDividido = document.getElementById('dividido-inputs');
  const alertaMonto = document.getElementById('alerta-monto');
  let totalActual = 0;

  // Evento para abrir el modal desde cualquier botón de cobrar
  document.addEventListener('click', e => {
    const btn = e.target.closest('.cobrar-btn');
    if (!btn) return;

    const salaId = btn.getAttribute('data-sala-id');
    const ticket = document.querySelector(`#ticket_${salaId}`);
    const totalLinea = ticket?.querySelector('div:last-child span')?.textContent || '$0';
    totalActual = parseFloat(totalLinea.replace(/[^0-9,.]/g, '').replace(',','.')) || 0;

    formCobro.reset();
    divDividido.style.display = 'none';
    alertaMonto.classList.add('d-none');

    // Llenar datos en el modal
    inpSalaId.value = salaId;
    inpTotal.value = totalActual.toFixed(2);
    txtTotal.textContent = totalActual.toFixed(2);

    // Obtener cliente del formulario de la sala
    const clienteInput = document.querySelector(`#form_sala_${salaId} input[name="cliente"]`);
    inpCliente.value = clienteInput ? clienteInput.value : '';

    // Mostrar modal
    bsModal.show();
  });

  // Mostrar/ocultar inputs para pago dividido
  document.querySelectorAll('input[name="forma_pago"]').forEach(input => {
    input.addEventListener('change', function() {
      divDividido.style.display = (this.value === 'dividido') ? 'block' : 'none';
    });
  });

  // Enviar formulario de cobro
  formCobro.addEventListener('submit', async e => {
    e.preventDefault();
    const formaPago = document.querySelector('input[name="forma_pago"]:checked').value;
    let efectivo = 0;
    let transferencia = 0;

    if (formaPago === 'dividido') {
      efectivo = parseFloat(document.getElementById('input-efectivo').value || 0);
      transferencia = parseFloat(document.getElementById('input-transferencia').value || 0);
      if (Math.abs((efectivo + transferencia) - totalActual) > 0.01) {
        alertaMonto.classList.remove('d-none');
        return;
      }
    } else if (formaPago === 'efectivo') {
      efectivo = totalActual;
    } else {
      transferencia = totalActual;
    }

    const formData = new FormData(formCobro);
    formData.append('efectivo', efectivo);
    formData.append('transferencia', transferencia);
    formData.append('sala_id', inpSalaId.value);
    formData.append('monto', inpTotal.value);
    formData.append('forma_pago', formaPago);

    // Obtener datos necesarios
    const horaInicio = document.querySelector(`#form_sala_${inpSalaId.value} .hora-inicio`).value;
    const duracionMin = parseInt(document.querySelector(`#form_sala_${inpSalaId.value} input[name="duracion"]`).value) || 0;

    formData.append('hora_inicio', horaInicio);
    formData.append('hora_fin', '23:59');
    formData.append('duracion', duracionMin);

    // Obtener precio desde ajax
    let base = 0;
    try {
      const res = await fetch('ajax/ajax_precio_sala.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          sala_id: inpSalaId.value,
          hora: horaInicio
        })
      });
      const data = await res.json();
      base = parseFloat(data.precio) * (duracionMin / 60);
    } catch (e) {
      alert('Error al calcular precio sala');
      return;
    }

    formData.append('precio_sala', base.toFixed(2));

    // Productos
    const productos = [];
    document.querySelectorAll(`#productos_${inpSalaId.value} li`).forEach(li => {
      const nombre = li.textContent.trim().replace('🗑', '').trim();
      const precio = parseFloat(li.dataset.precio || 0);
      productos.push({
        nombre,
        precio,
        cantidad: 1
      });
    });
    formData.append('productos_json', JSON.stringify(productos));

    // Alquileres
    const alquileres = [];
    document.querySelectorAll(`#alquileres_${inpSalaId.value} li`).forEach(li => {
      alquileres.push({
        nombre: li.textContent.trim().replace('🗑', '').trim(),
        precio: parseFloat(li.dataset.precio)
      });
    });
    formData.append('alquileres', JSON.stringify(alquileres));

    const descuento = parseFloat(document.querySelector(`#form_sala_${inpSalaId.value} .descuento-input`).value) || 0;
    formData.append('descuento', descuento);

    // Enviar al servidor
    fetch('ajax/guardar_cobro_sala.php', {
      method: 'POST',
      body: formData
    })
    .then(r => r.json())
    .then(data => {
      if (data.success && data.ticket_id) {
        const modalBody = document.querySelector('#modalCobroSala .modal-content');
        modalBody.innerHTML = `
          <div class="p-3 text-center">
            <h5 class="text-success mb-3">✅ COBRO REGISTRADO</h5>
            <div class="d-flex justify-content-center gap-3">
              <button onclick="window.open('ver_ticket_sala.php?id=${data.ticket_id}', '_blank')" class="btn btn-primary">
                VER TICKET
              </button>
              <button onclick="window.open('ver_ticket_sala.php?id=${data.ticket_id}&print=1', '_blank')" class="btn btn-secondary">
                IMPRIMIR
              </button>
              <button onclick="location.reload()" class="btn btn-success">
                FINALIZAR
              </button>
            </div>
          </div>
        `;
      } else {
        alert('❌ Error al guardar el cobro');
      }
    })
    .catch(() => alert('❌ Error al conectar con el servidor'));
  });
});

// Funcionalidad para mesas
function abrirModalCobroMesa(id) {
  const ticket = document.querySelector(`#ticket_mesa_${id}`);
  const totalLinea = ticket?.querySelector('div:last-child span')?.textContent || '$0';
  const total = parseFloat(totalLinea.replace(/[^0-9.,]/g, '').replace(',', '.')) || 0;

  document.getElementById('mesa-id').value = id;
  document.getElementById('mesa-total').value = total;
  document.getElementById('mesa-total-visible').value = `$${total.toFixed(2)}`;
  document.getElementById('mesa-cliente').value = '';
  document.getElementById('mesa-comentario').value = '';
  document.getElementById('mesa-forma-pago').value = '';
  document.getElementById('mesa-dividido').style.display = 'none';
  document.getElementById('mesa-ver-ticket').classList.add('d-none');
  const modal = new bootstrap.Modal(document.getElementById('modalCobroMesa'));
  modal.show();
}

document.getElementById("mesa-forma-pago").addEventListener("change", function () {
  document.getElementById("mesa-dividido").style.display = this.value === "dividido" ? "flex" : "none";
});

document.getElementById('formCobroMesa').addEventListener('submit', function(e) {
  e.preventDefault();
  const btn = document.querySelector('#formCobroMesa button[type="submit"]');
  btn.disabled = true;

  const formData = new FormData(this);
  const forma = document.getElementById('mesa-forma-pago').value;
  const total = parseFloat(document.getElementById('mesa-total').value) || 0;

  if (forma === 'efectivo') {
    formData.set('efectivo', total.toFixed(2));
    formData.set('transferencia', 0);
  } else if (forma === 'transferencia') {
    formData.set('efectivo', 0);
    formData.set('transferencia', total.toFixed(2));
  } else if (forma === 'dividido') {
    const efec = parseFloat(document.getElementById('mesa-efectivo').value) || 0;
    const trans = parseFloat(document.getElementById('mesa-transferencia').value) || 0;
    formData.set('efectivo', efec);
    formData.set('transferencia', trans);
  }

  const mesaId = document.getElementById('mesa-id').value;

  const productosSeleccionados = [];
  document.querySelectorAll(`#productos_mesa_${mesaId} li`).forEach(item => {
    const precio = parseFloat(item.dataset.precio);
    productosSeleccionados.push({ precio });
  });

  formData.append('productos_json', JSON.stringify(productosSeleccionados));

  fetch('ajax/guardar_cobro_mesa.php', {
    method: 'POST',
    body: formData
  })
  .then(res => res.json())
  .then(data => {
    if (data.success && data.ticket_id) {
      const modalContent = document.querySelector('#modalCobroMesa .modal-content');
      modalContent.innerHTML = `
        <div class="p-3 text-center">
          <h5 class="text-success mb-3">✅ COBRO REGISTRADO</h5>
          <div class="d-flex justify-content-center gap-3">
            <button onclick="window.open('ver_ticket_mesa.php?id=${data.ticket_id}', '_blank')" class="btn btn-primary">
              VER TICKET
            </button>
            <button onclick="window.open('ver_ticket_mesa.php?id=${data.ticket_id}&print=1', '_blank')" class="btn btn-secondary">
              IMPRIMIR
            </button>
            <button onclick="location.reload()" class="btn btn-success">
              FINALIZAR
            </button>
          </div>
        </div>
      `;
    } else {
      alert('❌ Error: ' + (data.error || 'Error desconocido'));
    }
  })
  .catch(() => alert('❌ Error al guardar'))
  .finally(() => {
    btn.disabled = false;
  });
});

// Persistencia de formularios
function getStorageKey(idSala) { return `form_sala_${idSala}`; }

function initAutoSave(idSala) {
  const iframe = document.getElementById(`iframe_sala_${idSala}`);
  iframe.addEventListener('load', () => {
    const doc = iframe.contentDocument || iframe.contentWindow.document;
    const form = doc.getElementById(`form_sala_${idSala}`);
    if (!form) return;

    const saved = localStorage.getItem(getStorageKey(idSala));
    if (saved) {
      const data = JSON.parse(saved);
      Object.entries(data).forEach(([name, value]) => {
        const field = form.elements[name];
        if (field) field.value = value;
      });
    }

    form.addEventListener('input', () => {
      const data = {};
      [...form.elements].forEach(el => {
        if (el.name) data[el.name] = el.value;
      });
      localStorage.setItem(getStorageKey(idSala), JSON.stringify(data));
    });
  });
}

['1', '2', 'Bandas', 'H', 'M'].forEach(initAutoSave);
</script>
</body>
</html>