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

// Agregar producto
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['accion'] === 'agregar') {
  $nombre = trim($_POST['nombre']);
  $precio = floatval($_POST['precio']);
  $stock_input = trim($_POST['stock']);
  $stock = ($stock_input === '') ? null : intval($stock_input);

  if ($nombre !== '' && $precio >= 0) {
    if (is_null($stock)) {
      $stmt = mysqli_prepare($con, "INSERT INTO productos_mesas (nombre, precio, stock, visible) VALUES (?, ?, NULL, 1)");
      mysqli_stmt_bind_param($stmt, 'sd', $nombre, $precio);
    } else {
      $stmt = mysqli_prepare($con, "INSERT INTO productos_mesas (nombre, precio, stock, visible) VALUES (?, ?, ?, 1)");
      mysqli_stmt_bind_param($stmt, 'sdi', $nombre, $precio, $stock);
    }
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
  }
  header("Location: admin_productos_mesas.php");
  exit;
}

// Editar producto
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['accion'] === 'editar') {
  $id = intval($_POST['id']);
  $nombre = trim($_POST['nombre']);
  $precio = floatval($_POST['precio']);
  $stock_input = trim($_POST['stock']);
  $stock = ($stock_input === '') ? null : intval($stock_input);

  if ($id > 0 && $nombre !== '' && $precio >= 0) {
    if (is_null($stock)) {
      $stmt = mysqli_prepare($con, "UPDATE productos_mesas SET nombre = ?, precio = ?, stock = NULL WHERE id = ?");
      mysqli_stmt_bind_param($stmt, 'sdi', $nombre, $precio, $id);
    } else {
      $stmt = mysqli_prepare($con, "UPDATE productos_mesas SET nombre = ?, precio = ?, stock = ? WHERE id = ?");
      mysqli_stmt_bind_param($stmt, 'sdii', $nombre, $precio, $stock, $id);
    }
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
  }
  header("Location: admin_productos_mesas.php");
  exit;
}

// Borrar producto
if (isset($_GET['borrar']) && is_numeric($_GET['borrar'])) {
  $id = intval($_GET['borrar']);
  mysqli_query($con, "UPDATE productos_mesas SET visible = 0 WHERE id = $id LIMIT 1");
  header("Location: admin_productos_mesas.php");
  exit;
}

$res = mysqli_query($con, "SELECT * FROM productos_mesas WHERE visible = 1 ORDER BY id DESC");
$productos = mysqli_fetch_all($res, MYSQLI_ASSOC);
?>

<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Admin Productos Mesas</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    .tachito { color: #dc3545; text-decoration: none; font-size: 1.2em; }
    .tachito:hover { color: #a00; }
    .editar-btn { font-size: 0.9em; }
  </style>
</head>
<body class="bg-light">
<div class="container py-4">
  <h2 class="mb-4">🛒 Productos (Mesas)</h2>

  <form method="POST" class="row g-3 mb-4">
    <input type="hidden" name="accion" value="agregar">
    <div class="col-md-4">
      <input type="text" name="nombre" class="form-control" placeholder="Nombre del producto" required>
    </div>
    <div class="col-md-3">
      <input type="number" name="precio" class="form-control" step="0.01" min="0" placeholder="Precio" required>
    </div>
    <div class="col-md-3">
      <input type="number" name="stock" class="form-control" placeholder="Stock (opcional)">
    </div>
    <div class="col-md-2">
      <button type="submit" class="btn btn-success w-100">Agregar</button>
    </div>
  </form>

  <div class="table-responsive">
    <table class="table table-bordered table-sm bg-white align-middle">
      <thead class="table-light">
        <tr><th>ID</th><th>Producto</th><th>Precio</th><th>Stock</th><th style="width: 100px;">Acciones</th></tr>
      </thead>
      <tbody>
        <?php foreach ($productos as $p): ?>
          <tr>
            <form method="POST">
              <input type="hidden" name="accion" value="editar">
              <input type="hidden" name="id" value="<?= $p['id'] ?>">
              <td><?= $p['id'] ?></td>
              <td><input type="text" name="nombre" class="form-control form-control-sm" value="<?= htmlspecialchars($p['nombre']) ?>" required></td>
              <td><input type="number" name="precio" class="form-control form-control-sm" step="0.01" min="0" value="<?= $p['precio'] ?>" required></td>
              <td><input type="number" name="stock" class="form-control form-control-sm" value="<?= $p['stock'] ?>" <?= is_null($p['stock']) ? '' : 'required' ?>></td>
              <td>
                <button type="submit" class="btn btn-sm btn-primary editar-btn">💾</button>
                <a href="?borrar=<?= $p['id'] ?>" class="tachito ms-2" onclick="return confirm('¿Eliminar este producto?')">🗑️</a>
              </td>
            </form>
          </tr>
        <?php endforeach; ?>
        <?php if (count($productos) === 0): ?>
          <tr><td colspan="5" class="text-center text-muted">No hay productos cargados.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>
</body>
</html>
