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

// Crear sala
if (isset($_POST['crear_sala'])) {
    $nombre = trim($_POST['nombre']);
    if ($nombre != '') {
        mysqli_query($con, "INSERT INTO salas (nombre, en_index) VALUES ('$nombre', 0)");
    }
    header("Location: admin_salas.php");
    exit;
}

// Cambiar visibilidad en index
if (isset($_GET['toggle'])) {
    $id = intval($_GET['toggle']);
    $sala = mysqli_fetch_assoc(mysqli_query($con, "SELECT en_index FROM salas WHERE id = $id"));
    if ($sala) {
        $nuevo = $sala['en_index'] ? 0 : 1;
        mysqli_query($con, "UPDATE salas SET en_index = $nuevo WHERE id = $id");
    }
    header("Location: admin_salas.php");
    exit;
}

// Eliminar sala (si no tiene franjas)
if (isset($_GET['borrar_sala'])) {
    $id = intval($_GET['borrar_sala']);
    $check = mysqli_query($con, "SELECT id FROM precios_horarios WHERE sala_id = $id");
    if (mysqli_num_rows($check) === 0) {
        mysqli_query($con, "DELETE FROM salas WHERE id = $id");
    }
    header("Location: admin_salas.php");
    exit;
}

// Agregar franja
if (isset($_POST['agregar_franja'])) {
    $sala_id = intval($_POST['sala_id']);
    $desde = $_POST['desde'];
    $hasta = $_POST['hasta'];
    $precio = floatval($_POST['precio']);
    mysqli_query($con, "INSERT INTO precios_horarios (sala_id, desde_hora, hasta_hora, precio_hora, precio_visual) VALUES ($sala_id, '$desde', '$hasta', $precio, $precio)");
    header("Location: admin_salas.php?sala_id=$sala_id");
    exit;
}

// Borrar franja
if (isset($_GET['borrar_franja'])) {
    $id = intval($_GET['borrar_franja']);
    $res = mysqli_fetch_assoc(mysqli_query($con, "SELECT sala_id FROM precios_horarios WHERE id = $id"));
    if ($res) {
        mysqli_query($con, "DELETE FROM precios_horarios WHERE id = $id");
        header("Location: admin_salas.php?sala_id=" . $res['sala_id']);
        exit;
    }
}

// Obtener salas
$salas = mysqli_query($con, "SELECT * FROM salas ORDER BY id ASC");

// Sala activa para precios
$sala_id = isset($_GET['sala_id']) ? intval($_GET['sala_id']) : 0;
$franjas = [];
if ($sala_id) {
    $res_franjas = mysqli_query($con, "SELECT * FROM precios_horarios WHERE sala_id = $sala_id ORDER BY desde_hora");
    while ($f = mysqli_fetch_assoc($res_franjas)) {
        $franjas[] = $f;
    }
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Administrar Salas</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<div class="container py-4">
  <h2 class="mb-4">⚙️ Administrar Salas</h2>

  <!-- Crear nueva sala -->
  <form method="post" class="mb-4 row g-2">
    <div class="col-md-6">
      <input type="text" name="nombre" class="form-control" placeholder="Nombre de la nueva sala" required>
    </div>
    <div class="col-md-3">
      <button type="submit" name="crear_sala" class="btn btn-success w-100">Crear sala</button>
    </div>
  </form>

  <!-- Listado de salas -->
  <div class="card mb-4">
    <div class="card-header bg-dark text-white">Salas registradas</div>
    <div class="card-body">
      <ul class="list-group">
        <?php while ($s = mysqli_fetch_assoc($salas)): ?>
          <li class="list-group-item d-flex justify-content-between align-items-center">
            <div>
              <strong><?= htmlspecialchars($s['nombre']) ?></strong>
              <span class="text-muted ms-2">[ID <?= $s['id'] ?>]</span>
            </div>
            <div>
              <a href="?toggle=<?= $s['id'] ?>" class="btn btn-sm btn-outline-<?= $s['en_index'] ? 'danger' : 'primary' ?>">
                <?= $s['en_index'] ? 'Quitar del index' : 'Añadir al index' ?>
              </a>
              <a href="?sala_id=<?= $s['id'] ?>" class="btn btn-sm btn-outline-secondary">Configurar precios</a>
              <a href="?borrar_sala=<?= $s['id'] ?>" class="btn btn-sm btn-outline-warning" onclick="return confirm('¿Eliminar esta sala?')">Eliminar</a>
            </div>
          </li>
        <?php endwhile; ?>
      </ul>
    </div>
  </div>

  <!-- Agregar franja horaria -->
  <?php if ($sala_id): ?>
    <div class="card mb-4">
      <div class="card-header bg-warning">🕒 Franjas horarias para Sala ID <?= $sala_id ?></div>
      <div class="card-body">
        <form method="post" class="row g-2 mb-3">
          <input type="hidden" name="sala_id" value="<?= $sala_id ?>">
          <div class="col-md-3">
            <input type="time" name="desde" class="form-control" required>
          </div>
          <div class="col-md-3">
            <input type="time" name="hasta" class="form-control" required>
          </div>
          <div class="col-md-3">
            <input type="number" name="precio" step="0.01" class="form-control" placeholder="Precio por hora" required>
          </div>
          <div class="col-md-3">
            <button type="submit" name="agregar_franja" class="btn btn-success w-100">Agregar franja</button>
          </div>
        </form>

        <ul class="list-group">
          <?php foreach ($franjas as $f): ?>
            <li class="list-group-item d-flex justify-content-between align-items-center">
              <?= $f['desde_hora'] ?> → <?= $f['hasta_hora'] ?> @ $<?= number_format($f['precio_hora'], 2) ?>
              <a href="?borrar_franja=<?= $f['id'] ?>" class="btn btn-sm btn-outline-danger">Eliminar</a>
            </li>
          <?php endforeach; ?>
        </ul>
      </div>
    </div>
  <?php endif; ?>

</div>
</body>
</html>
