<?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;
$targetStatus = isset($_POST['status']) ? trim((string)$_POST['status']) : '';
$currentAdminId = isset($_SESSION['admin_id']) ? (int)$_SESSION['admin_id'] : 0;
$currentAdminUsername = isset($_SESSION['admin_username']) ? (string)$_SESSION['admin_username'] : 'admin';

if ($adminId <= 0 || ($targetStatus !== 'enabled' && $targetStatus !== 'disabled')) {
    redirect('/admin/user/list.php?toggle_status=invalid');
}

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

    write_admin_operation_log($currentAdminId, $currentAdminUsername, isset($result['id']) ? (int)$result['id'] : $adminId, $result['username'], $targetStatus === 'disabled' ? 'disable_admin' : 'enable_admin', '切换管理员状态为：' . $targetStatus);

    $statusKey = $targetStatus === 'disabled' ? 'success_disabled' : 'success_enabled';
    redirect('/admin/user/list.php?toggle_status=' . $statusKey . '&toggled_admin=' . urlencode($result['username']));
} catch (Exception $e) {
    if (strpos($e->getMessage(), '当前登录管理员不允许禁用自己的账号') !== false) {
        redirect('/admin/user/list.php?toggle_status=self_protected');
    }

    if (strpos($e->getMessage(), '至少需要保留 1 个启用状态的管理员账号') !== false) {
        redirect('/admin/user/list.php?toggle_status=protected');
    }

    if (strpos($e->getMessage(), '未找到对应的管理员记录') !== false) {
        redirect('/admin/user/list.php?toggle_status=missing');
    }

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