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

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Content-Type: application/json");
header("Access-Control-Max-Age: 86400");

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once(__DIR__ . '/../../config.php');

$input = json_decode(file_get_contents('php://input'), true);
$slug_tienda = trim($input['slug_tienda'] ?? '');
$zona_id     = isset($input['zona_id']) ? (int)$input['zona_id'] : 0;

if ($slug_tienda === '' || $zona_id <= 0) {
  echo json_encode(['success' => false, 'message' => 'Faltan slug_tienda o zona_id']);
  exit;
}

$sql = "SELECT id, zona_id, numero, capacidad, activo
        FROM pos_mesas
        WHERE slug_tienda=? AND zona_id=?
        ORDER BY numero ASC";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("si", $slug_tienda, $zona_id);
$stmt->execute();
$res = $stmt->get_result();

$mesas = [];
while ($r = $res->fetch_assoc()) $mesas[] = $r;

echo json_encode(['success' => true, 'mesas' => $mesas]);
$stmt->close();
$mysqli->close();
