<?php
require __DIR__ . '/../../app/bootstrap.php';
require __DIR__ . '/../../app/database.php';
require_login();

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}
require_csrf();
$adminId = isset($_POST['id']) ? (int)$_POST['id'] : 0;
$currentAdminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : 0;
$currentAdminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';

if ($adminId <= 0) {
    redirect('/admin/user/list.php?delete_status=invalid');
}

try {
    $result = delete_admin($adminId, $currentAdminId);
    if (!$result || empty($result['username'])) {
        redirect('/admin/user/list.php?delete_status=missing');
    }

    write_admin_operation_log($currentAdminId, $currentAdminUsername, isset($result['id']) ? (int)$result['id'] : $adminId, $result['username'], 'delete_admin', '删除管理员账号');

    redirect('/admin/user/list.php?delete_status=success&deleted_admin=' . urlencode($result['username']));
} catch (Exception $e) {
    if (strpos($e->getMessage(), '未找到对应的管理员记录') !== false) {
        redirect('/admin/user/list.php?delete_status=missing');
    }

    if (strpos($e->getMessage(), '当前登录管理员不允许删除自己的账号') !== false) {
        redirect('/admin/user/list.php?delete_status=self_protected');
    }

    if (strpos($e->getMessage(), '最后一个启用管理员不可删除') !== false) {
        redirect('/admin/user/list.php?delete_status=protected');
    }

    redirect('/admin/user/list.php?delete_status=error');
}
