<?php
require "../api.php";

$api = new spamhasiApi();
$conf = $api->getConf();

if (!$api->checkAuth()) {
    die('{"status":500, "error":"Unauthorized"}');
}

if (!isset($_POST["id"])) {
    die('{"status":500, "error":"Missing fields"}');
}

$id = intval($_POST["id"]);

$db = $api->getDB();

$sql = "SELECT COUNT(*) FROM users";
$stmt = $db->query($sql);

$count = $stmt->fetchColumn();

if ($count == 1) {
    die('{"status":500, "error":"Der einzige Benutzer darf NICHT GELÖSCHT WERDEN!"}');
}

$sql = "SELECT username FROM users WHERE id = :id";
$stmt = $db->prepare($sql);
$stmt->execute([':id' => $id]);
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$name = $result["username"];

$sql = "DELETE FROM users WHERE id = :id";
$stmt = $db->prepare($sql);

$sql_exec = $stmt->execute([':id' => $id]);

if (!$sql_exec) {
    die('{"status":500, "error":"SQL Error"}');
}

if (!unlink($conf["PATH"] . "/tmp/user_sessions/" . $name . ".json")) {
    die('{"status":500, "error":"Error to remove session file."}');
}

die('{"status":200}');
?>