<?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();

$isBatch = !empty($_POST['batch']);

if ($isBatch) {
    $ids = isset($_POST['ids']) && is_array($_POST['ids']) ? $_POST['ids'] : array();
    $ids = array_filter(array_map('intval', $ids), function ($v) { return $v > 0; });
    $ids = array_values(array_unique($ids));
    if (empty($ids)) {
        redirect('/admin/menu/list.php?delete_status=error');
    }
    $deleted = 0;
    $skipped = 0;
    foreach ($ids as $mid) {
        try {
            delete_menu($mid);
            $deleted++;
        } catch (Exception $e) {
            $skipped++;
        }
    }
    log_admin_action('menu_batch_delete', '批量删除菜单 ' . $deleted . ' 个，跳过 ' . $skipped . ' 个');
    redirect('/admin/menu/list.php?delete_status=success');
}

$id = isset($_POST['id']) ? (int)$_POST['id'] : 0;
if ($id <= 0) {
    redirect('/admin/menu/list.php?delete_status=error');
}

try {
    delete_menu($id);
    log_admin_action('menu_delete', '删除菜单 ID:' . $id);
    redirect('/admin/menu/list.php?delete_status=success');
} catch (Exception $e) {
    redirect('/admin/menu/list.php?delete_status=error');
}
