<?php
// public/api/webhook_settings.php
require_once __DIR__ . '/../../app/config.php';
require_once __DIR__ . '/../../app/db.php';

header('Content-Type: application/json; charset=utf-8');

if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }

function jexit($payload, $status=200){
  http_response_code($status);
  echo json_encode($payload, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
  exit;
}

if (empty($_SESSION['user']['id'])) jexit(['ok'=>false,'error'=>'Não autenticado'],401);

$pdo    = db();
$userId = $_SESSION['user']['id'];
$action = $_GET['action'] ?? '';

try {
  switch ($action) {
    case 'get':
      $q = $pdo->prepare("SELECT webhook_enabled, webhook_token, meta FROM users WHERE id=?");
      $q->execute([$userId]);
      jexit(['ok'=>true,'user'=>$q->fetch(PDO::FETCH_ASSOC)]);
    case 'toggle':
      $pdo->prepare("UPDATE users SET webhook_enabled = NOT COALESCE(webhook_enabled,false) WHERE id=?")->execute([$userId]);
      jexit(['ok'=>true]);
    case 'rotate':
      $newToken = bin2hex(random_bytes(16));
      $pdo->prepare("UPDATE users SET webhook_token=?, webhook_enabled=TRUE WHERE id=?")->execute([$newToken,$userId]);
      jexit(['ok'=>true,'new_token'=>$newToken]);
    // opcional: salve/test, se for usar depois
    default:
      jexit(['ok'=>false,'error'=>'Ação inválida'],400);
  }
} catch (Throwable $e) {
  jexit(['ok'=>false,'error'=>$e->getMessage()],500);
}
