<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(E_ALL);

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

/* =====================  CONFIGURACIÓN  ===================== */
$salaId = 11;                             // ⚠️ Cloná y cambiá solo esto

/* =====================  DATOS SALA  ===================== */
$sala = mysqli_fetch_assoc(mysqli_query($con,"SELECT * FROM salas WHERE id = $salaId LIMIT 1"));
if(!$sala){
  die("<h3 style='color:red'>Sala $salaId no existe</h3>");
}

/* =====================  CATÁLOGOS  ===================== */
$productos  = mysqli_fetch_all(mysqli_query($con,"SELECT * FROM productos  ORDER BY nombre"), MYSQLI_ASSOC);
$alquileres = mysqli_fetch_all(mysqli_query($con,"SELECT * FROM alquileres ORDER BY nombre"), MYSQLI_ASSOC);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Sala <?= htmlspecialchars($sala['nombre']) ?></title>
<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>
<style>
:root {
  --primary: #4361ee;
  --primary-dark: #3a56d4;
  --danger: #f72585;
  --success: #4cc9f0;
  --light: #f8f9fa;
  --dark: #212529;
  --gray: #6c757d;
  
  --border-radius: 6px;
  --box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  --transition: all 0.25s ease;
}

body {
  background: #f5f7fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  line-height: 1.4;
}

/* Card Container Super Compacta */
.sala-card {
  max-width: 360px;
  width: 100%;
  margin: 10px auto;
  background: #EEF3D6;
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
  overflow: hidden;
  border-top: 3px solid var(--primary);
}

/* Header Compacto */
.sala-card .card-header {
  padding: 12px 16px;
}

.sala-card .card-header h5 {
  font-size: 1.1rem;
  margin: 0;
  font-weight: 600;
  color: var(--dark);
}

/* Form Elements Ultra Compactos */
.form-label {
  font-size: 0.8rem;
  margin-bottom: 4px;
  color: var(--gray);
  font-weight: 500;
  display: block;
}

.form-control, .form-select {
  padding: 7px 10px;
  font-size: 0.85rem;
  border: 1px solid #e0e0e0;
  border-radius: var(--border-radius);
  width: 100%;
  margin-bottom: 8px;
}

.form-control:focus, .form-select:focus {
  outline: none;
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(67, 97, 238, 0.1);
}

/* Duration Controls Mini */
.duration-controls {
  display: flex;
  align-items: center;
  margin: 8px 0;
  gap: 6px;
}

.modificar-duracion {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  border: none;
  font-size: 0.7rem;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.modificar-duracion[data-minutos="-30"] {
  background-color: var(--danger);
  color: white;
}

.modificar-duracion[data-minutos="60"] {
  background-color: var(--success);
  color: white;
}

#duracion_<?= $salaId ?> {
  font-size: 0.85rem;
  font-weight: 500;
  min-width: 50px;
  text-align: center;
}

/* Listas Compactas */
.lista-productos, .lista-alquileres {
  max-height: 120px;
  overflow-y: auto;
  margin: 6px 0 10px;
  border: 1px solid #eee;
  border-radius: var(--border-radius);
}

.list-group-item {
  padding: 6px 10px;
  font-size: 0.8rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
}

.btn-remove {
  background: none;
  border: none;
  color: var(--danger);
  font-size: 0.9rem;
  cursor: pointer;
  padding: 2px;
  opacity: 0.7;
}

.btn-remove:hover {
  opacity: 1;
}

/* Ticket Box Mini */
.ticket-box {
  background: white;
  border-radius: var(--border-radius);
  padding: 10px 12px;
  margin: 12px 0 8px;
  font-size: 0.8rem;
  border-left: 2px solid var(--primary);
}

.ticket-box > div {
  display: flex;
  justify-content: space-between;
  padding: 3px 0;
}

.ticket-box > div:last-child {
  font-weight: 600;
  color: var(--primary);
  margin-top: 4px;
  padding-top: 4px;
  border-top: 1px dashed #eee;
}

/* Botón Cobrar Pro Compacto */
.cobrar-btn {
  width: 100%;
  padding: 8px;
  background: var(--primary);
  color: white;
  border: none;
  border-radius: var(--border-radius);
  font-size: 0.85rem;
  font-weight: 500;
  cursor: pointer;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.cobrar-btn:hover {
  background: var(--primary-dark);
}

/* Scrollbar Minimalista */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 2px;
}
</style>
</head>
<body class="p-2">
<body style="background-color: #fff59d;">
<!-- =========== CARD SALA =========== -->
<form class="card p-3 sala-card" id="form_sala_<?= $salaId ?>">
  <h5 class="mb-3">Sala <?= htmlspecialchars($sala['nombre']) ?></h5>

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

  <div class="mb-2">
    <label class="form-label">Productos</label>
    <select class="form-select producto-select">
      <option value="">-- Agregar producto --</option>
      <?php foreach($productos as $p): ?>
        <option value="<?= $p['id'] ?>" data-precio="<?= $p['precio'] ?>">
          <?= htmlspecialchars($p['nombre']) ?> ($<?= number_format($p['precio'],2) ?>)
        </option>
      <?php endforeach; ?>
    </select>
    <ul class="list-group mt-1 lista-productos" id="productos_<?= $salaId ?>"></ul>
  </div>

  <div class="mb-2">
    <label class="form-label">Alquileres</label>
    <select class="form-select alquiler-select">
      <option value="">-- Agregar alquiler --</option>
      <?php foreach($alquileres as $a): ?>
        <option value="<?= $a['id'] ?>" data-precio="<?= $a['precio'] ?>">
          <?= htmlspecialchars($a['nombre']) ?> ($<?= number_format($a['precio'],2) ?>)
        </option>
      <?php endforeach; ?>
    </select>
    <ul class="list-group mt-1 lista-alquileres" id="alquileres_<?= $salaId ?>"></ul>
  </div>

  <div class="mb-2">
    <label class="form-label">Descuento (%)</label>
    <input type="number" class="form-control descuento-input" name="descuento" value="0" min="0" max="100">
  </div>
  
  <div class="mb-2">
    <label class="form-label">Hora de inicio</label>
    <input type="time" class="form-control hora-inicio" name="hora" value="<?= date('H:i') ?>">
  </div>
  
  <div class="mb-2">
    <label class="form-label d-block">Duración</label>
    <button type="button" class="btn btn-danger btn-sm modificar-duracion" data-minutos="-30">-30m</button>
    <span class="mx-2" id="duracion_<?= $salaId ?>">0:00h</span>
    <button type="button" class="btn btn-success btn-sm modificar-duracion" data-minutos="60">+1h</button>
    <input type="hidden" name="duracion" value="0">
  </div>

  <div class="ticket-box" id="ticket_<?= $salaId ?>">
    Ticket:
    <div>Precio Sala: $0</div>
    <div>Productos: -</div>
    <div>Alquileres: -</div>
    <div>Descuento: 0%</div>
    <div>Total: $0</div>
  </div>

  <div class="text-end mt-2">
    <button type="button" class="btn btn-success btn-sm cobrar-btn">💰 Cerrar sala y cobrar</button>
  </div>
</form>

<!-- =========== MODAL COBRO =========== -->
<div class="modal fade" id="modalCobroSala" tabindex="-1">
  <div class="modal-dialog">
    <div class="modal-content">
      <!-- Paso 1: formulario -->
      <form id="formCobroSala" class="p-3">
        <h5 class="mb-3">💰 Cobro Sala</h5>
        <input type="hidden" name="sala_id" value="<?= $salaId ?>">
        <input type="hidden" id="modal-total" name="monto">

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

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

        <div class="mb-2 fs-5">Total: $<span id="texto-total">0</span></div>

        <div class="mb-2">
          <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-2" 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="text-end"><button type="submit" class="btn btn-primary">Confirmar cobro</button></div>
      </form>

      <!-- Paso 2: post-cobro -->
      <div id="postCobro" class="p-3 d-none">
        <h5 class="mb-3 text-success">✅ Cobro registrado</h5>
        <p>Ticket generado correctamente.</p>
        <div class="d-flex gap-2">
          <a id="btn-ver-ticket" href="#" target="_blank" class="btn btn-outline-primary btn-sm">Ver ticket</a>
          <button type="button" id="btn-imprimir" class="btn btn-outline-secondary btn-sm">Imprimir</button>
          <button type="button" id="btn-finalizar" class="btn btn-success btn-sm">Finalizar</button>
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
/* ========== TICKET EN VIVO (usa ajax/ajax_precio_sala.php) ========== */
function actualizarTicket(){
  const hora = $('.hora-inicio').val();
  const dur  = parseInt($('input[name=duracion]').val())||0;
  const desc = parseFloat($('.descuento-input').val())||0;

  $.post('ajax/ajax_precio_sala.php', { sala_id: <?= $salaId ?>, hora: hora }, function(r){
      const precioHora = parseFloat(r.precio);
      const base = precioHora * (dur/60);

      let prod = 0, alq = 0;
      $('#productos_<?= $salaId ?> li').each((_,li)=>prod += parseFloat($(li).data('precio')));
      $('#alquileres_<?= $salaId ?> li').each((_,li)=>alq += parseFloat($(li).data('precio')));

      const sub = base + prod + alq;
      const tot = sub - (sub*desc/100);

      $('#ticket_<?= $salaId ?>').html(`Ticket:
        <div>Precio Sala: $${base.toFixed(2)}</div>
        <div>Productos: $${prod.toFixed(2)}</div>
        <div>Alquileres: $${alq.toFixed(2)}</div>
        <div>Descuento: ${desc}%</div>
        <div>Total: $${tot.toFixed(2)}</div>`);
      $('.cobrar-btn').data('total',tot.toFixed(2));
  },'json');
}

/* ========== EVENTOS BÁSICOS ========== */
$(document).on('input change','.hora-inicio,.descuento-input',actualizarTicket);

$(document).on('click','.modificar-duracion',function(){
  let v=parseInt($('input[name=duracion]').val())||0;
  v=Math.max(0,v+parseInt($(this).data('minutos')));
  $('input[name=duracion]').val(v);
  $('#duracion_<?= $salaId ?>').text((v/60).toFixed(2)+'h');
  actualizarTicket();
});

$(document).on('change','.producto-select',function(){
  const opt=$(this).find('option:selected'); if(!opt.val()) return;
  $('#productos_<?= $salaId ?>').append(
    `<li class="list-group-item d-flex justify-content-between align-items-center" data-precio="${opt.data('precio')}">
      ${opt.text()} <button type="button" class="btn btn-sm btn-outline-danger btn-remove">🗑</button>
    </li>`
  ); $(this).val(''); actualizarTicket();
});

$(document).on('change','.alquiler-select',function(){
  const opt=$(this).find('option:selected'); if(!opt.val()) return;
  $('#alquileres_<?= $salaId ?>').append(
    `<li class="list-group-item d-flex justify-content-between align-items-center" data-precio="${opt.data('precio')}">
      ${opt.text()} <button type="button" class="btn btn-sm btn-outline-danger btn-remove">🗑</button>
    </li>`
  ); $(this).val(''); actualizarTicket();
});

$(document).on('click','.btn-remove',function(){ $(this).closest('li').remove(); actualizarTicket(); });

/* ========== MODAL COBRO ========== */
$(document).on('click','.cobrar-btn',function(){
  const tot=$(this).data('total')||0;
  $('#texto-total').text(tot); $('#modal-total').val(tot);
  $('#modal-cliente').val($('input[name=cliente]').val());
  $('#formCobroSala').removeClass('d-none'); $('#postCobro').addClass('d-none');
  new bootstrap.Modal('#modalCobroSala').show();
});

$('input[name=forma_pago]').on('change',e=>$('#dividido-inputs').toggle(e.target.value==='dividido'));

$('#formCobroSala').on('submit', function(e) {
  e.preventDefault();
  const total = parseFloat($('#modal-total').val());
  const forma = $('input[name=forma_pago]:checked').val();
  let ef = 0, tr = 0;

  if (forma === 'efectivo') ef = total;
  else if (forma === 'transferencia') tr = total;
  else {
    ef = parseFloat($('#input-efectivo').val()) || 0;
    tr = parseFloat($('#input-transferencia').val()) || 0;
    if (Math.abs((ef + tr) - total) > 0.01) {
      $('#alerta-monto').removeClass('d-none');
      return;
    }
  }

  const hora_inicio = $('.hora-inicio').val();
  const duracion = parseInt($('input[name=duracion]').val()) || 0;
  const descuento = parseFloat($('.descuento-input').val()) || 0;
  const productos = $('#productos_<?= $salaId ?> li').map(function () {
    return { id: $(this).data('id'), nombre: $(this).clone().children().remove().end().text().trim(), precio: $(this).data('precio') };
  }).get();
  const alquileres = $('#alquileres_<?= $salaId ?> li').map(function () {
    return { id: $(this).data('id'), nombre: $(this).clone().children().remove().end().text().trim(), precio: $(this).data('precio') };
  }).get();

  const precioSala = parseFloat($('#ticket_<?= $salaId ?> div:nth-child(1)').text().replace(/[^\d.-]/g, '')) || 0;

  const fd = new FormData(this);
  fd.append('efectivo', ef);
  fd.append('transferencia', tr);
  fd.append('hora_inicio', hora_inicio);
  fd.append('hora_fin', '');
  fd.append('duracion', duracion);
  fd.append('precio_sala', precioSala);
  fd.append('descuento', descuento);
  fd.append('productos_json', JSON.stringify(productos));
  fd.append('alquileres', JSON.stringify(alquileres));

  fetch('ajax/guardar_cobro_sala.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(resp => {
      if (resp.success && resp.ticket_id) {
        window.ticketIdSala = resp.ticket_id;
        $('#btn-ver-ticket').attr('href', 'ver_ticket_sala.php?id=' + resp.ticket_id);
        $('#formCobroSala').addClass('d-none');
        $('#postCobro').removeClass('d-none');
      } else {
        alert('Error al guardar el cobro');
      }
    })
    .catch(() => alert('Sin conexión con el servidor'));
});

/* ========== BOTONES POST-COBRO ========== */
$('#btn-imprimir').on('click',()=>{ if(window.ticketIdSala) window.open('ver_ticket_sala.php?id='+window.ticketIdSala,'_blank').print(); });

$('#btn-finalizar').off('click').on('click',()=>{
  document.getElementById('form_sala_<?= $salaId ?>').reset();
  // Limpiar hora, duración, descuento y listas dinámicas
  $('.hora-inicio').val('<?= date("H:i") ?>');
  $('input[name=duracion]').val(0);
  $('.descuento-input').val(0);
  $('#productos_<?= $salaId ?>, #alquileres_<?= $salaId ?>').empty();
  $('#duracion_<?= $salaId ?>').text('0:00h');
  // Refrescar ticket
  actualizarTicket();
  // Cerrar modal si sigue abierto
  const modal = bootstrap.Modal.getInstance(document.getElementById('modalCobroSala'));
  if(modal) modal.hide();
  // Avisar al index para refrescar totales de caja
  window.parent.postMessage({tipo:'actualizarCaja'}, '*');
  // Limpiar localStorage
  localStorage.removeItem('form_sala_<?= $salaId ?>');
});

/* ========== Persistencia LocalStorage (sin horarios) ========== */
const STORAGE_KEY_SALA1 = 'form_sala_<?= $salaId ?>';

function collectState(){
  const data = {
    cliente: $('input[name="cliente"]').val() || '',
    descuento: $('.descuento-input').val() || '0',
    productos: $('#productos_<?= $salaId ?> li').map(function(){return {texto: $(this).clone().children().remove().end().text().trim(), precio: $(this).data('precio')}}).get(),
    alquileres: $('#alquileres_<?= $salaId ?> li').map(function(){return {texto: $(this).clone().children().remove().end().text().trim(), precio: $(this).data('precio')}}).get()
  };
  localStorage.setItem(STORAGE_KEY_SALA1, JSON.stringify(data));
}

function restoreState(){
  const json = localStorage.getItem(STORAGE_KEY_SALA1);
  
  if(!json) return;

  try{
    const data = JSON.parse(json);
    $('input[name="cliente"]').val(data.cliente||'');
    $('.descuento-input').val(data.descuento||'0');

    // restaurar listas
    $('#productos_<?= $salaId ?>').empty();
    (data.productos||[]).forEach(p=>{
      $('#productos_<?= $salaId ?>').append(`<li class="list-group-item d-flex justify-content-between align-items-center" data-id="${p.id}" data-precio="${p.precio}">${p.texto} <button type="button" class="btn btn-sm btn-outline-danger btn-remove">🗑</button></li>`);
    });
    $('#alquileres_<?= $salaId ?>').empty();
    (data.alquileres||[]).forEach(a=>{
      $('#alquileres_<?= $salaId ?>').append(`<li class="list-group-item d-flex justify-content-between align-items-center" data-precio="${a.precio}">${a.texto} <button type="button" class="btn btn-sm btn-outline-danger btn-remove">🗑</button></li>`);
    });
  }catch(e){}
  actualizarTicket();
}

$(function(){
  restoreState();
  // Guardar en cada cambio (excepto horarios)
  $(document).on('input change', 'input[name="cliente"], .descuento-input', collectState);
  $(document).on('click', '.btn-remove', collectState);
  $(document).on('change', '.producto-select, .alquiler-select', collectState);
});

/* Inicial */
actualizarTicket();
</script>
</body>
</html>