<?php
define('TONSUI_LOADED', true);
require_once __DIR__ . '/session_init.php';
requireAdmin(true);
require_once __DIR__ . '/db.php';

try {
  $data = json_decode(file_get_contents('php://input'), true) ?: [];
  $user_id = intval($data['user_id'] ?? 0);
  $suspended = intval(!empty($data['account_suspended']));
  $transfers = intval(!empty($data['transfers_suspended']));
  $dormant = intval(!empty($data['account_dormant']));
  if ($user_id <= 0) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Invalid user id']); exit; }

  $has = ['account_suspended'=>false,'transfers_suspended'=>false,'account_dormant'=>false];
  $cols = $pdo->query("SHOW COLUMNS FROM users");
  while ($c = $cols->fetch(PDO::FETCH_ASSOC)) {
    $f = strtolower($c['Field'] ?? '');
    if (isset($has[$f])) $has[$f] = true;
  }
  if (!$has['account_suspended'] || !$has['transfers_suspended'] || !$has['account_dormant']) {
    http_response_code(500); echo json_encode(['success'=>false,'message'=>'Required columns missing']); exit;
  }

  if ($dormant) $transfers = 1; // dormant implies transfers suspended

  $stmt = $pdo->prepare("UPDATE users SET account_suspended=?, transfers_suspended=?, account_dormant=? WHERE id=?");
  $stmt->execute([$suspended, $transfers, $dormant, $user_id]);

  echo json_encode(['success'=>true,'flags'=>[
    'account_suspended'=>$suspended,
    'transfers_suspended'=>$transfers,
    'account_dormant'=>$dormant
  ]]);
} catch (Throwable $e) {
  http_response_code(500);
  echo json_encode(['success'=>false,'message'=>'Server error']);
}
