<?php
// ==============================================
// Visualizador de Tablas (solo registros de HOY)
// Oculta automáticamente la columna ID_USUARIO
// ==============================================
session_start();

if (!isset($_SESSION['id_usuario'])) {
  header('Location: Login_LG.html?error=Sesion expirada'); exit;
}
if (($_SESSION['rol'] ?? '') !== 'CAJA') {
  header('Location: home.php?error=sin_permiso'); exit;
}

// Sesión
$idUsuario    = $_SESSION['id_usuario'] ?? '';
$rol          = $_SESSION['rol'] ?? '';
$nombreCajero = $_SESSION['nombre_cajero'] ?? $idUsuario;

// Conexión
require_once __DIR__ . '/../backend/database/Conexion_SQL_Server.php';
if ($conn === false) { die('❌ Error de conexión a BD.'); }

// --- Funciones auxiliares ---
function q_all_assoc($conn, string $sql, array $params = []): array {
  $stmt = sqlsrv_query($conn, $sql, $params, ["Scrollable" => SQLSRV_CURSOR_KEYSET]);
  if ($stmt === false) { error_log(print_r(sqlsrv_errors(), true)); return []; }
  $rows = [];
  while ($r = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
    foreach ($r as $k => $v) {
      if ($v instanceof DateTimeInterface) $r[$k] = $v->format('Y-m-d H:i:s');
    }
    $rows[] = $r;
  }
  sqlsrv_free_stmt($stmt);
  return $rows;
}
function q_scalar_colnames($conn, string $table): array {
  $sql = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS
          WHERE TABLE_NAME = ? ORDER BY ORDINAL_POSITION";
  $cols = q_all_assoc($conn, $sql, [$table]);
  return array_map(fn($r) => $r['COLUMN_NAME'], $cols);
}

// --- Tablas y columnas de fecha ---
$tables = [
  "PROPINA_FISICO"         => "FECHA_REG_FISICO",
  "PROPINA_TARJETA"        => "FECHA_REG_TARJETA",
  "REPORTE_POS"            => "FECHA_REG_POS",
  "INFORME_DESCUENTO"      => "FECHA_REG_DESCUENTO",
  "INFORME_CORTESIA"       => "FECHA_REG_CORTESIA",
  "INFORME_NOTA_CREDITO"   => "FECHA_REG_NOTA_CREDITO",
  "INFORME_GASTO"          => "FECHA_REG_GASTO",
  "INFORME_ELIMINADO"      => "FECHA_REG_ELIMINADO",
];

// --- Datos de hoy ---
$data = [];
$headers = [];
foreach ($tables as $table => $dateCol) {
  $sql = "SELECT * FROM {$table}
          WHERE CONVERT(date, {$dateCol}) = CONVERT(date, GETDATE())
          ORDER BY 1 DESC";
  $rows = q_all_assoc($conn, $sql);

  // 🔸 Filtrar la columna ID_USUARIO de headers
  $headersRaw = !empty($rows) ? array_keys($rows[0]) : q_scalar_colnames($conn, $table);
  $headers[$table] = array_filter($headersRaw, fn($h) => strtoupper($h) !== 'ID_USUARIO');

  // 🔸 Eliminar ID_USUARIO de cada fila
  foreach ($rows as &$r) {
    unset($r['ID_USUARIO']);
  }
  unset($r);

  $data[$table] = $rows;
}

$hoyStr = date('Y-m-d');
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <title>Visualizador (Hoy <?= htmlspecialchars($hoyStr) ?>)</title>
  <meta name="viewport" content="width=device-width, initial-scale=1" />

  <!-- Bootstrap + Icons -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css">
  <link rel="stylesheet" href="../css/Estilos_appCaja.css">

  <!-- Estilo de tabla -->
  <style>
    .nav-tabs .nav-link { cursor:pointer; }

    .table-wrap{
      border-radius:16px;
      overflow:auto;
      max-height:62vh;
      border:1px solid rgba(255,255,255,.10);
      box-shadow:0 12px 36px rgba(0,0,0,.35);
      background:rgba(17,22,27,.65);
      backdrop-filter: blur(2px);
    }

    .table-guardiana{
      margin:0;
      color:#EAECEF;
      font-size:.92rem;
      width:100%;
    }
    .table-guardiana thead th{
      position: sticky; top: 0; z-index: 2;
      background: linear-gradient(180deg,#1f2937,#161d27);
      color:#EDEFF3;
      border-bottom:1px solid rgba(255,255,255,.12);
      text-transform:uppercase; letter-spacing:.3px; font-weight:900;
      padding:.5rem .65rem;
      white-space: nowrap;
    }
    .table-guardiana tbody tr{ background: rgba(35,42,52,.68); }
    .table-guardiana tbody tr:nth-child(even){ background: rgba(35,42,52,.52); }
    .table-guardiana tbody tr:hover{ background: rgba(31,182,229,.12); }
    .table-guardiana td{
      padding:.45rem .65rem;
      vertical-align:middle;
      border-color:rgba(255,255,255,.08);
      white-space:nowrap;
    }
    .text-num { text-align:right; font-variant-numeric: tabular-nums; }
  </style>
</head>
<body>
  <div class="bg-overlay"></div>

  <!-- Header -->
  <header class="header-lg">
    <div class="header-left">
      <div class="header-avatar"><i class="bi bi-person-fill"></i></div>
      <div class="header-user">
        <span class="header-name"><?= htmlspecialchars($nombreCajero, ENT_QUOTES, 'UTF-8') ?></span>
        <span class="header-role"><?= htmlspecialchars($rol, ENT_QUOTES, 'UTF-8') ?></span>
      </div>
    </div>
    <div class="d-flex align-items-center gap-2">
      <a href="./app_Caja.php" class="btn btn-dark btn-cta" style="width:auto;padding:10px 14px;">
        <i class="bi bi-arrow-left"></i> Volver a Caja
      </a>
      <form action="../backend/procesos/seguridad/logout.php" method="post" class="m-0"
            onsubmit="return confirm('¿Deseas cerrar sesión?');">
        <button type="submit" class="btn-logout">
          <i class="bi bi-box-arrow-right"></i> Cerrar sesión
        </button>
      </form>
    </div>
  </header>

  <main class="container container-guardiana">
    <section class="panel-card mt-2">
      <h1 class="h-title">Visualizador de Datos — Solo Hoy</h1>
      <div class="subtle">Fecha: <strong><?= htmlspecialchars($hoyStr) ?></strong></div>
      <div class="rule-rose"></div>

      <!-- Tabs -->
      <ul class="nav nav-tabs" id="tabTables" role="tablist">
        <?php $i=0; foreach ($tables as $table => $dateCol): ?>
          <li class="nav-item" role="presentation">
            <button class="nav-link <?= $i===0?'active':'' ?>" id="tab-<?= $table ?>-tab"
                    data-bs-toggle="tab" data-bs-target="#tab-<?= $table ?>" type="button" role="tab">
              <?= htmlspecialchars($table) ?>
            </button>
          </li>
        <?php $i++; endforeach; ?>
      </ul>

      <div class="tab-content pt-2" id="tabTablesContent">
        <?php $i=0; foreach ($tables as $table => $dateCol): ?>
          <div class="tab-pane fade <?= $i===0?'show active':'' ?>" id="tab-<?= $table ?>" role="tabpanel">
            <div class="table-wrap mt-2">
              <table class="table-guardiana">
                <thead>
                  <tr>
                    <?php foreach ($headers[$table] as $col): ?>
                      <th><?= htmlspecialchars($col) ?></th>
                    <?php endforeach; ?>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($data[$table] as $row): ?>
                    <tr>
                      <?php foreach ($headers[$table] as $col): ?>
                        <?php
                          $isNumber = preg_match('/(MONTO|MON_|CANT|CANTIDAD|TOTAL|PRECIO|ID_POS|DECIMAL|INT)$/i', $col);
                          $tdClass  = $isNumber ? 'text-num' : '';
                        ?>
                        <td class="<?= $tdClass ?>"><?= htmlspecialchars((string)($row[$col] ?? '')) ?></td>
                      <?php endforeach; ?>
                    </tr>
                  <?php endforeach; ?>
                  <?php if (empty($data[$table])): ?>
                    <tr>
                      <td colspan="<?= max(1,count($headers[$table])) ?>" class="text-center text-muted">
                        No hay registros para hoy.
                      </td>
                    </tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        <?php $i++; endforeach; ?>
      </div>
    </section>
  </main>

  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
