<?php
if (!defined('IN_INDEX')) { header("Location: /painel/dashboard/"); exit(); }
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

$ALLOW_TABLES = ['apostas_esportivas','ticker_partidas'];

$table = $_GET['tab'] ?? $ALLOW_TABLES[0];
if (!in_array($table, $ALLOW_TABLES, true)) $table = $ALLOW_TABLES[0];

$_SESSION['csrf_tables'] ??= bin2hex(random_bytes(32));

function getPrimaryKey(PDO $pdo, string $table): ?string {
  $stmt = $pdo->prepare("
    SELECT COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = ?
      AND COLUMN_KEY = 'PRI'
    LIMIT 1
  ");
  $stmt->execute([$table]);
  $r = $stmt->fetch(PDO::FETCH_ASSOC);
  return $r['COLUMN_NAME'] ?? null;
}

function getColumns(PDO $pdo, string $table): array {
  $stmt = $pdo->prepare("
    SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, EXTRA
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE TABLE_SCHEMA = DATABASE()
      AND TABLE_NAME = ?
    ORDER BY ORDINAL_POSITION
  ");
  $stmt->execute([$table]);
  return $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];
}

$pk = getPrimaryKey($pdo, $table);
$cols = getColumns($pdo, $table);

if (!$pk) {
  echo "<div class='alertanao'>Tabela <b>{$table}</b> sem PRIMARY KEY. Precisa ter um ID (PK) pra editar com segurança.</div>";
  exit;
}

$colNames = array_map(fn($c) => $c['COLUMN_NAME'], $cols);
$colsSql = implode(",", array_map(fn($c) => "`{$c}`", $colNames));

$rows = $pdo->query("SELECT {$colsSql} FROM `{$table}` ORDER BY `{$pk}` DESC LIMIT 500")->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="container-conteudo">
  <h2 class="titulo-funcoes">Editar tabela: <b><?= htmlspecialchars($table) ?></b></h2>

  <div style="display:flex; gap:10px; margin:10px 0;">
    <a class="submit-button" href="?page=tabelas_admin&tab=apostas_esportivas" style="text-decoration:none; padding:10px 14px;">Apostas</a>
    <a class="submit-button" href="?page=tabelas_admin&tab=ticker_partidas" style="text-decoration:none; padding:10px 14px;">Ticker</a>
    <button class="submit-button" type="button" onclick="openCreate()">+ Novo</button>
  </div>

  <div style="overflow:auto; border-radius:12px; border:1px solid #1e293b;">
    <table style="width:100%; border-collapse:collapse; background:#0b1220; color:#e5e7eb;">
      <thead>
        <tr>
          <?php foreach ($colNames as $c): ?>
            <th style="padding:10px; border-bottom:1px solid #1e293b; text-align:left; white-space:nowrap;"><?= htmlspecialchars($c) ?></th>
          <?php endforeach; ?>
          <th style="padding:10px; border-bottom:1px solid #1e293b;">Ações</th>
        </tr>
      </thead>
      <tbody>
        <?php foreach ($rows as $r): ?>
          <tr>
            <?php foreach ($colNames as $c): ?>
              <td style="padding:10px; border-bottom:1px solid #111827; white-space:nowrap;">
                <?= htmlspecialchars((string)($r[$c] ?? '')) ?>
              </td>
            <?php endforeach; ?>
            <td style="padding:10px; border-bottom:1px solid #111827; white-space:nowrap;">
              <button class="submit-button" type="button" style="padding:6px 10px;" onclick='openEdit(<?= json_encode($r, JSON_UNESCAPED_UNICODE) ?>)'>Editar</button>
              <button class="submit-button" type="button" style="padding:6px 10px; background:#ef4444;" onclick="delRow('<?= htmlspecialchars((string)$r[$pk]) ?>')">Apagar</button>
            </td>
          </tr>
        <?php endforeach; ?>
        <?php if (!$rows): ?>
          <tr><td colspan="<?= count($colNames)+1 ?>" style="padding:14px;">Sem registros.</td></tr>
        <?php endif; ?>
      </tbody>
    </table>
  </div>
</div>

<!-- MODAL -->
<div id="modalEditRow" class="modal" style="display:none;">
  <div class="modal-content">
    <span class="close-modal" onclick="closeModal()"><i class="fas fa-times"></i></span>
    <h2 id="modalTitle">Editar</h2>
    <div id="alerta-table"></div>

    <form id="formTableRow">
      <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_tables'] ?>">
      <input type="hidden" name="table" value="<?= htmlspecialchars($table) ?>">
      <input type="hidden" name="pk" value="<?= htmlspecialchars($pk) ?>">
      <input type="hidden" name="mode" id="mode" value="edit">
      <input type="hidden" name="pk_value" id="pk_value" value="">

      <div id="fields"></div>

      <button class="submit-button espacobutton" type="submit">Salvar</button>
    </form>
  </div>
</div>

<script>
const PK = <?= json_encode($pk) ?>;
const COLS = <?= json_encode($cols, JSON_UNESCAPED_UNICODE) ?>;

function closeModal(){
  document.getElementById('modalEditRow').style.display = 'none';
}
function openModal(){
  document.getElementById('modalEditRow').style.display = 'block';
}

function buildFields(data, isCreate=false){
  const wrap = document.getElementById('fields');
  wrap.innerHTML = '';

  COLS.forEach(col => {
    const name = col.COLUMN_NAME;
    const extra = (col.EXTRA || '').toLowerCase();
    if (!isCreate && name === PK) return; // não edita PK
    if (isCreate && name === PK && extra.includes('auto_increment')) return; // não pede auto increment

    const val = (data && data[name] != null) ? data[name] : (col.COLUMN_DEFAULT ?? '');
    const type = (col.DATA_TYPE || '').toLowerCase();

    let inputType = 'text';
    if (['int','bigint','decimal','float','double'].includes(type)) inputType = 'number';
    if (['date'].includes(type)) inputType = 'date';
    if (['datetime','timestamp'].includes(type)) inputType = 'datetime-local';

    const row = document.createElement('div');
    row.className = 'form-row';
    row.innerHTML = `
      <div class="input-icon">
        <i class="fas fa-pen"></i>
        <input type="${inputType}"
               name="data[${name}]"
               placeholder="${name}"
               value="${String(val).replaceAll('"','&quot;')}"
               ${col.IS_NULLABLE === 'NO' ? 'required' : ''}>
      </div>
    `;
    wrap.appendChild(row);
  });
}

function openEdit(row){
  document.getElementById('modalTitle').innerText = 'Editar registro';
  document.getElementById('mode').value = 'edit';
  document.getElementById('pk_value').value = row[PK];
  buildFields(row, false);
  openModal();
}

function openCreate(){
  document.getElementById('modalTitle').innerText = 'Novo registro';
  document.getElementById('mode').value = 'create';
  document.getElementById('pk_value').value = '';
  buildFields({}, true);
  openModal();
}

async function delRow(pkValue){
  if(!confirm('Apagar este registro?')) return;

  const fd = new FormData();
  fd.append('csrf_token', <?= json_encode($_SESSION['csrf_tables']) ?>);
  fd.append('table', <?= json_encode($table) ?>);
  fd.append('pk', PK);
  fd.append('pk_value', pkValue);

  const res = await fetch('php/tabelas_delete.php', {
    method: 'POST',
    body: fd,
    headers: {"X-Requested-With":"XMLHttpRequest"}
  });

  const data = await res.json().catch(()=>null);
  if(data && data.ok){ location.reload(); }
  else alert(data?.error || 'Erro ao apagar');
}

document.getElementById('formTableRow').addEventListener('submit', async (e)=>{
  e.preventDefault();

  const alerta = document.getElementById('alerta-table');
  alerta.innerHTML = "<p>Salvando...</p>";

  const fd = new FormData(e.target);

  const res = await fetch('php/tabelas_save.php', {
    method: 'POST',
    body: fd,
    headers: {"X-Requested-With":"XMLHttpRequest"}
  });

  const data = await res.json().catch(()=>null);
  if(!data){ alerta.innerHTML = "<p class='alertanao'>Resposta inválida.</p>"; return; }

  if(data.ok){
    alerta.innerHTML = "<p class='alertasim'>Salvo!</p>";
    setTimeout(()=>location.reload(), 400);
  } else {
    alerta.innerHTML = "<p class='alertanao'>"+(data.error || 'Erro')+"</p>";
  }
});
</script>
