<?php
/**
 * mapa_mesas_vertical.php  – edición limpia 20‑Jul‑2025
 * --------------------------------------------------------
 * ▸ Mapa ARRIBA (arrastrable)
 * ▸ Inventario + Config. ABAJO
 * ▸ Movés las mesas libremente → «Guardar posiciones» persiste todo en BD.
 * ▸ Al refrescar, se cargan desde BD y quedan fijas.
 */

session_start();
require 'conexion.php';

date_default_timezone_set('America/Argentina/Buenos_Aires');

// ⚙️ Ajustes rápidos
const IFRAME_H = 420; // alto total del iframe
const MAP_H    = 300; // alto visible del mapa
const MESA_SZ  = 32;  // tamaño del bloque mesa
const INV_W    = 60;  // ancho inventario

/* ---------- Garantizar columnas (una sola vez) ---------- */
function ensure($con,$col,$sql){
  if(!mysqli_num_rows(mysqli_query($con,"SHOW COLUMNS FROM mesas LIKE '$col'")))
      mysqli_query($con,$sql);
}
ensure($con,'pos_x', "ALTER TABLE mesas ADD COLUMN pos_x INT UNSIGNED NOT NULL DEFAULT 0");
ensure($con,'pos_y', "ALTER TABLE mesas ADD COLUMN pos_y INT UNSIGNED NOT NULL DEFAULT 0");
ensure($con,'placed',"ALTER TABLE mesas ADD COLUMN placed TINYINT(1) NOT NULL DEFAULT 0");

/* ---------- Guardado individual (drag‑and‑drop live) ---------- */
if(isset($_POST['mesa_id'])){
  header('Content-Type: application/json');
  $id = intval($_POST['mesa_id']);
  $x  = intval($_POST['x'] ?? 0);
  $y  = intval($_POST['y'] ?? 0);
  $p  = intval($_POST['placed']);
  $st = $con->prepare("UPDATE mesas SET pos_x=?, pos_y=?, placed=? WHERE id=? LIMIT 1");
  $st->bind_param('iiii', $x, $y, $p, $id);
  echo json_encode(['success' => $st->execute()]);
  exit;
}

/* ---------- Guardado MASIVO desde botón ---------- */
if(isset($_POST['save_bulk'])){
  header('Content-Type: application/json');
  $arr = json_decode($_POST['data'] ?? '[]', true);
  if(!$arr || !is_array($arr)){
    echo json_encode(['success'=>false,'msg'=>'Datos vacíos']);
    exit;
  }

  // Iniciar transacción (si InnoDB)
  $supportsTx = ($con->query("SHOW VARIABLES LIKE 'tx_isolation'")->num_rows > 0);
  if($supportsTx) $con->begin_transaction();

  $st = $con->prepare("UPDATE mesas SET pos_x=?, pos_y=?, placed=? WHERE id=? LIMIT 1");
  foreach($arr as $m){
    $x = intval($m['x']);
    $y = intval($m['y']);
    $p = intval($m['placed']);
    $id= intval($m['id']);
    $st->bind_param('iiii',$x,$y,$p,$id);
    if(!$st->execute()){
      if($supportsTx) $con->rollback();
      echo json_encode(['success'=>false,'msg'=>'DB error: '.mysqli_error($con)]);
      exit;
    }
  }
  if($supportsTx) $con->commit();
  echo json_encode(['success'=>true,'count'=>count($arr)]);
  exit;
}

/* ---------- Datos para dibujar ---------- */
$mesas = mysqli_fetch_all(mysqli_query($con,
  "SELECT id,nombre,pos_x,pos_y,placed FROM mesas ORDER BY id"), MYSQLI_ASSOC);
$inv   = array_filter($mesas, fn($m)=>$m['placed']==0);
$plano = array_filter($mesas, fn($m)=>$m['placed']==1);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Mapa Mesas</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css">
<style>
:root {
  --mesa: <?=MESA_SZ?>px;
  --inv: <?=INV_W?>px;
  --color-mesa: #1976d2;
  --color-hover: #1565c0;
}

html, body {
  margin: 0;
  height: 100%;
  overflow: hidden;
  background: black;
  font-size: 13px;
  font-family: "Segoe UI", Roboto, sans-serif;
  color: #333;
}

#wrap {
  display: flex;
  flex-direction: column;
  height: <?=IFRAME_H?>px;
  border: 1px solid #cdd5e0;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  background: #fff;
}

/* 🗺️ Mapa de mesas */
#mapa {
  height: <?=MAP_H?>px;
  background: url('img/floorplan.svg') center/contain no-repeat;
  position: relative;
  overflow: hidden;
  border-bottom: 1px solid #d6e4f0;
}

/* Zona inferior */
#zona {
  flex: 1;
  display: flex;
}

#inv {
  width: var(--inv);
  background: #e9f1fa;
  padding: 10px;
  border-right: 1px solid #ccd;
  overflow-y: auto;
  text-align: center;
}

#cfg {
  flex: 1;
  padding: 12px;
  background: #f8fbff;
  overflow-y: auto;
}

/* Mesas */
.mesa {
  width: var(--mesa);
  height: var(--mesa);
  background: var(--color-mesa);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  font-size: 13px;
  color: #fff;
  cursor: grab;
  user-select: none;
  position: absolute;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  transition: transform 0.12s, background-color 0.2s;
}

.mesa:hover {
  transform: scale(1.08);
  background-color: var(--color-hover);
}

#inv .mesa {
  position: relative;
  margin: 6px auto;
  top: 0;
  left: 0;
  background-color: #64b5f6;
  color: #08326b;
  box-shadow: none;
}

.lbl {
  position: absolute;
  top: 2px;
  left: 4px;
  font-size: 10px;
  color: #555;
}

/* Botón guardar */
#btnGuardar {
  margin-top: 8px;
}

</style>
</head>
<body>
<div id="wrap">
  <!-- 🗺️ MAPA -->
  <div id="mapa">
    <?php foreach($plano as $m): ?>
      <div class="mesa" data-id="<?=$m['id']?>" style="left:<?=$m['pos_x']?>px; top:<?=$m['pos_y']?>px; position:absolute;">
        <?=htmlspecialchars($m['nombre'])?>
      </div>
    <?php endforeach; ?>
  </div>



<!-- modal realtime -->
<div class="modal fade" id="modalMesa" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered">
    <div class="modal-content bg-dark text-white">
      <div class="modal-header border-0">
        <h5 class="modal-title">Mesa <span id="modalNum"></span></h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body p-0">
        <iframe id="modalIframe" src="" style="width:100%;height:70vh;border:0;"></iframe>
      </div>
    </div>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function(){
  // helper para draggable
  function makeDrag($e){
    $e.draggable({helper:'clone',revert:'invalid',start:()=>{$e.css('opacity',.4)},stop:()=>{$e.css('opacity',1)}});
  }
  makeDrag($('.mesa'));

  // drop en mapa
  $('#mapa').droppable({accept:'.mesa',drop:function(e,ui){const $m=ui.draggable;const mapOffset=$(this).offset();$m.appendTo('#mapa');$m.css({position:'absolute',left:ui.offset.left-mapOffset.left,top:ui.offset.top-mapOffset.top});makeDrag($m);}});
  // drop en inventario
  $('#inv').droppable({accept:'.mesa',drop:function(e,ui){const $m=ui.draggable;$m.css({position:'relative',left:'',top:''}).appendTo('#inv');makeDrag($m);}});

  // abrir modal realtime al click
  $(document).on('click','.mesa',function(){const id=$(this).data('id');$('#modalNum').text(id);$('#modalIframe').attr('src',`mesa_${id}.php?embed=1&ts=${Date.now()}`);bootstrap.Modal.getOrCreateInstance('#modalMesa').show();});

  // Guardar posiciones en bloque
  $('#btnGuardar').on('click',function(){const arr=[];$('.mesa').each(function(){const $m=$(this);const id=$m.data('id');const placed=$m.parent().attr('id')==='mapa'?1:0;let x=0,y=0;if(placed){x=parseInt($m.css('left'))||0;y=parseInt($m.css('top'))||0;}arr.push({id,x,y,placed});});
    $.post(location.pathname,{save_bulk:1,data:JSON.stringify(arr)},function(d){if(d.success){alert('Posiciones guardadas ✅');}else{alert('Error: '+(d.msg||'desconocido'));}},'json');});
});
// Ya debés tener algo así al crear el modal
const miModal = new bootstrap.Modal(document.getElementById('modalMesa'), {});

// Cuando el usuario lo cierra:
document.getElementById('modalMesa').addEventListener('hidden.bs.modal', () => {
  window.top.postMessage({ action: 'modal_closed' }, '*');
});

</script>
</body>
</html>
