<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../../config.php';
session_start();

if (!isset($_SESSION['usuario_id']) || ($_SESSION['usuario_tipo'] ?? '') !== 'admin') {
  echo json_encode(['ok'=>false,'error'=>'Não autorizado']); exit;
}

if (($_SERVER['HTTP_X_REQUESTED_WITH'] ?? '') !== 'XMLHttpRequest') {
  echo json_encode(['ok'=>false,'error'=>'Requisição inválida']); exit;
}

if (empty($_POST['csrf_token']) || empty($_SESSION['csrf_tables']) || !hash_equals($_SESSION['csrf_tables'], $_POST['csrf_token'])) {
  echo json_encode(['ok'=>false,'error'=>'CSRF inválido']); exit;
}

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

$table = $_POST['table'] ?? '';
$pk    = $_POST['pk'] ?? '';
$mode  = $_POST['mode'] ?? 'edit';
$pkVal = $_POST['pk_value'] ?? '';
$data  = $_POST['data'] ?? [];

if (!in_array($table, $ALLOW_TABLES, true)) { echo json_encode(['ok'=>false,'error'=>'Tabela inválida']); exit; }
if (!preg_match('/^[a-zA-Z0-9_]+$/', $pk)) { echo json_encode(['ok'=>false,'error'=>'PK inválida']); exit; }

// pega colunas reais da tabela
$pdo = conectarDB(); // ou $pdo global do seu projeto
if (!$pdo) { echo json_encode(['ok'=>false,'error'=>'Sem conexão']); exit; }

$stmt = $pdo->prepare("
  SELECT COLUMN_NAME, EXTRA
  FROM INFORMATION_SCHEMA.COLUMNS
  WHERE TABLE_SCHEMA = DATABASE()
    AND TABLE_NAME = ?
");
$stmt->execute([$table]);
$cols = $stmt->fetchAll(PDO::FETCH_ASSOC);

$realCols = [];
$autoIncPK = false;
foreach ($cols as $c) {
  $realCols[$c['COLUMN_NAME']] = true;
  if ($c['COLUMN_NAME'] === $pk && stripos($c['EXTRA'] ?? '', 'auto_increment') !== false) $autoIncPK = true;
}

$clean = [];
foreach ($data as $k => $v) {
  if (!isset($realCols[$k])) continue;
  if ($k === $pk) continue;
  $clean[$k] = $v;
}

try {
  if ($mode === 'create') {
    // remove PK se auto increment
    if ($autoIncPK) unset($clean[$pk]);

    if (!$clean) { echo json_encode(['ok'=>false,'error'=>'Nenhum campo']); exit; }

    $fields = array_keys($clean);
    $sql = "INSERT INTO `{$table}` (`" . implode("`,`", $fields) . "`) VALUES (:" . implode(",:", $fields) . ")";
    $st = $pdo->prepare($sql);
    foreach ($clean as $k=>$v) $st->bindValue(":".$k, $v);
    $st->execute();
    echo json_encode(['ok'=>true]);
    exit;
  }

  // edit
  if ($pkVal === '' || $pkVal === null) { echo json_encode(['ok'=>false,'error'=>'PK vazia']); exit; }
  if (!$clean) { echo json_encode(['ok'=>false,'error'=>'Nada para atualizar']); exit; }

  $set = [];
  foreach ($clean as $k=>$v) $set[] = "`{$k}` = :{$k}";
  $sql = "UPDATE `{$table}` SET " . implode(",", $set) . " WHERE `{$pk}` = :__pk LIMIT 1";
  $st = $pdo->prepare($sql);
  foreach ($clean as $k=>$v) $st->bindValue(":".$k, $v);
  $st->bindValue(":__pk", $pkVal);
  $st->execute();

  echo json_encode(['ok'=>true]);
} catch (Throwable $e) {
  echo json_encode(['ok'=>false,'error'=>'Erro: '.$e->getMessage()]);
}
