<?php
header('Content-Type: application/json; charset=utf-8');
session_start();
if (empty($_SESSION['user_id']) || empty($_SESSION['is_admin'])) { http_response_code(403); echo json_encode(['success'=>false,'message'=>'Access denied']); exit; }

$userId = isset($_POST['user_id']) ? (int)$_POST['user_id'] : 0; if (!$userId) { http_response_code(400); echo json_encode(['success'=>false,'message'=>'Invalid user']); exit; }

$dbPath = __DIR__ . '/db_config.php'; if (file_exists($dbPath)) require $dbPath;

if (isset($conn) && $conn) {
    $stmt = @$conn->prepare('DELETE FROM subadmins WHERE user_id = ?');
    if ($stmt) { $stmt->bind_param('i',$userId); $stmt->execute(); $stmt->close(); }
    echo json_encode(['success'=>true]); exit;
}

// JSON fallback
$f = __DIR__ . '/data/subadmins.json';
if (file_exists($f)) {
    $arr = json_decode(file_get_contents($f), true);
    if (!is_array($arr)) $arr = [];
    $arr = array_values(array_filter($arr, function($x) use ($userId){ return !isset($x['user_id']) || $x['user_id'] != $userId; }));
    file_put_contents($f, json_encode($arr, JSON_PRETTY_PRINT));
}
echo json_encode(['success'=>true]); exit;

?>
