<?php
require_once __DIR__ . "/../config/session.php";
require_once __DIR__ . "/../config/config.php";

header('Content-Type: application/json');

if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
  echo json_encode(['ok' => false, 'error' => 'Not logged in']); exit;
}
if (($_SESSION["role"] ?? "user") !== "admin") {
  echo json_encode(['ok' => false, 'error' => 'Forbidden']); exit;
}

// CSRF check
$csrf = $_POST['csrf'] ?? '';
if (empty($_SESSION['csrf']) || !hash_equals($_SESSION['csrf'], $csrf)) {
  echo json_encode(['ok' => false, 'error' => 'CSRF']); exit;
}

$id = (int)($_POST['id'] ?? 0);
if ($id <= 0) { echo json_encode(['ok'=>false,'error'=>'Invalid id']); exit; }

// Optional: sich selbst nicht
if ($id === (int)($_SESSION['id'] ?? 0)) {
  echo json_encode(['ok'=>false,'error'=>'Not allowed for yourself']); exit;
}

try {
  $stmt = $pdo->prepare("DELETE FROM remember_tokens WHERE user_id = :uid");
  $stmt->execute([':uid' => $id]);
  echo json_encode(['ok' => true]);
} catch (Throwable $e) {
  echo json_encode(['ok' => false, 'error' => 'DB error']);
}
