<?php
$authApp = 'configuracion';
session_start();
require __DIR__ . '/../../config/auth.php';
require __DIR__ . '/../../../../../config/db2.php';
require __DIR__ . '/../../lib/helpers.php';

if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE mrbs_room SET disabled = 1 - disabled WHERE id=?")->execute([(int)$_GET['toggle']]);
    $fRedir = ['f_nombre' => trim($_GET['f_nombre'] ?? ''), 'f_area' => $_GET['f_area'] ?? '', 'f_disabled' => $_GET['f_disabled'] ?? ''];
    header('Location: listarSalas.php?' . http_build_query($fRedir));
    exit;
}

$paginaActual = 'configuracion';
require __DIR__ . '/../../config/menu.php';

// Ordenamiento
$cols_ok = ['id', 'room_name', 'enCalendario', 'area_id', 'capacity', 'piso', 'ordenPagina', 'disabled'];
$sort = in_array($_GET['sort'] ?? '', $cols_ok, true) ? $_GET['sort'] : 'ordenPagina';
$dir  = strtoupper($_GET['dir'] ?? 'ASC') === 'DESC' ? 'DESC' : 'ASC';
$nextDir = $dir === 'ASC' ? 'DESC' : 'ASC';
$ind  = $dir === 'ASC' ? '▲' : '▼';
function sortLink($col, $lbl, $sort, $dir, $nextDir, $ind, $f) {
    $d = ($sort === $col) ? $nextDir : 'ASC';
    $q = http_build_query(array_merge($f, ['sort' => $col, 'dir' => $d]));
    return '<a href="?' . $q . '">' . $lbl . ($sort === $col ? ' ' . $ind : '') . '</a>';
}

// Filtros
$f = [
    'f_nombre'  => trim($_GET['f_nombre'] ?? ''),
    'f_area'    => $_GET['f_area'] ?? '',
    'f_disabled'=> $_GET['f_disabled'] ?? '',
];

$where  = [];
$params = [];
if ($f['f_nombre'])   { $where[] = "(r.room_name LIKE ? OR r.enCalendario LIKE ?)"; $params[] = '%'.$f['f_nombre'].'%'; $params[] = '%'.$f['f_nombre'].'%'; }
if ($f['f_area'] !== '') { $where[] = "r.area_id = ?"; $params[] = (int)$f['f_area']; }
if ($f['f_disabled'] !== '') { $where[] = "r.disabled = ?"; $params[] = (int)$f['f_disabled']; }

$wSql = $where ? 'WHERE ' . implode(' AND ', $where) : '';

$sql = "SELECT r.*, a.area_name
        FROM mrbs_room r
        LEFT JOIN mrbs_area a ON a.id = r.area_id
        $wSql
        ORDER BY $sort $dir";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);


// Areas para filtro
$areas = $pdo->query("SELECT id, area_name FROM mrbs_area ORDER BY area_name")->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="ph">
  <div>
    <h1>Salas</h1>
    <div class="bc"><a href="<?= BASE_URL ?>/index.php">Inicio</a> › Configuración › Salas</div>
  </div>
  <?php if (perm('configuracion','agregar')): ?><a href="crearSala.php" class="btn btn-p">+ Nueva Sala</a><?php endif; ?>
</div>

<?php if (isset($_GET['ok'])): ?>
  <div class="msg msg-ok">Sala guardada correctamente.</div>
<?php endif; ?>

<div class="card">
  <form method="GET" class="fb">
    <div class="fi">
      <label>Nombre / En Calendario</label>
      <input type="text" name="f_nombre" value="<?= htmlspecialchars($f['f_nombre']) ?>" placeholder="Buscar...">
    </div>
    <div class="fi">
      <label>Área</label>
      <select name="f_area">
        <option value="">Todas</option>
        <?php foreach ($areas as $a): ?>
          <option value="<?= $a['id'] ?>" <?= $f['f_area'] == $a['id'] ? 'selected' : '' ?>><?= htmlspecialchars($a['area_name']) ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="fi">
      <label>Estado</label>
      <select name="f_disabled">
        <option value="">Todos</option>
        <option value="0" <?= $f['f_disabled'] === '0' ? 'selected' : '' ?>>Activa</option>
        <option value="1" <?= $f['f_disabled'] === '1' ? 'selected' : '' ?>>Deshabilitada</option>
      </select>
    </div>
    <div class="fi" style="display:flex;align-items:flex-end;gap:6px">
      <button class="btn btn-p" type="submit">Filtrar</button>
      <a href="listarSalas.php" class="btn btn-g">Limpiar</a>
    </div>
    <input type="hidden" name="sort" value="<?= htmlspecialchars($sort) ?>">
    <input type="hidden" name="dir"  value="<?= htmlspecialchars($dir) ?>">
  </form>
</div>

<div style="margin-bottom:6px;font-size:13px;color:#475569"><?= count($rows) ?> resultado(s)</div>

<div class="tw">
  <table>
    <thead><tr>
      <th style="width:50px"><?= sortLink('id','ID',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th><?= sortLink('room_name','Nombre',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th><?= sortLink('enCalendario','En Calendario',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th><?= sortLink('area_id','Área',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th style="width:60px"><?= sortLink('capacity','Cap.',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th style="width:60px"><?= sortLink('piso','Piso',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th style="width:70px"><?= sortLink('ordenPagina','Orden',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th style="width:90px"><?= sortLink('disabled','Estado',$sort,$dir,$nextDir,$ind,$f) ?></th>
      <th style="width:130px">Acciones</th>
    </tr></thead>
    <tbody>
    <?php foreach ($rows as $row): ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td><?= htmlspecialchars($row['room_name'] ?? '') ?></td>
        <td><?= htmlspecialchars($row['enCalendario'] ?? '') ?></td>
        <td><?= htmlspecialchars($row['area_name'] ?? '') ?></td>
        <td style="text-align:center"><?= $row['capacity'] ?></td>
        <td style="text-align:center"><?= htmlspecialchars($row['piso'] ?? '') ?></td>
        <td style="text-align:center"><?= $row['ordenPagina'] ?></td>
        <td style="text-align:center">
          <?php if ($row['disabled']): ?>
            <span class="bp bp-r">Deshabilitada</span>
          <?php else: ?>
            <span class="bp bp-l">Activa</span>
          <?php endif; ?>
        </td>
        <td>
          <div class="ac">
            <?php if (perm('configuracion','editar')): ?><a href="crearSala.php?id=<?= $row['id'] ?>" class="btn btn-i btn-sm">Editar</a><?php endif; ?>
            <?php if (perm('configuracion','editar')): ?>
            <?php if ($row['disabled']): ?>
            <a href="?toggle=<?= $row['id'] ?>&<?= http_build_query($f) ?>"
               class="btn btn-s btn-sm"
               onclick="return confirm('¿Confirma la habilitación de la sala?')">Habilitar</a>
            <?php else: ?>
            <a href="?toggle=<?= $row['id'] ?>&<?= http_build_query($f) ?>"
               class="btn btn-r btn-sm"
               onclick="return confirm('¿Confirma la deshabilitación de la sala?')">Deshabilitar</a>
            <?php endif; ?>
            <?php endif; ?>
          </div>
        </td>
      </tr>
    <?php endforeach; ?>
    <?php if (!$rows): ?>
      <tr><td colspan="9" style="text-align:center;color:#94a3b8">Sin resultados</td></tr>
    <?php endif; ?>
    </tbody>
  </table>
</div>
</div></body></html>
