<?php
require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../includes/functions.php';

header('Content-Type: application/json');

// 检查登录状态
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

// 检查权限
$user = currentUser();
if ($user['role'] !== 'admin' && $user['role'] !== 'employee') {
    echo json_encode(['success' => false, 'message' => '权限不足']);
    exit;
}

// 获取参数
$order_id = intval($_POST['order_id'] ?? 0);
$order_no = trim($_POST['order_no'] ?? '');

if ($order_id <= 0 && empty($order_no)) {
    echo json_encode(['success' => false, 'message' => '参数错误']);
    exit;
}

// 查询订单
if ($order_id > 0) {
    $order = $db->fetchOne("SELECT status FROM orders WHERE id = $order_id");
} else {
    $order_no = $db->escape($order_no);
    $order = $db->fetchOne("SELECT status FROM orders WHERE order_no = '$order_no'");
}

if (!$order) {
    echo json_encode(['success' => false, 'message' => '订单不存在']);
    exit;
}

if ($order['status'] != 'pending') {
    echo json_encode(['success' => false, 'message' => '只能删除待支付的订单']);
    exit;
}

// 删除订单
if ($order_id > 0) {
    $db->query("DELETE FROM orders WHERE id = $order_id");
} else {
    $db->query("DELETE FROM orders WHERE order_no = '$order_no'");
}

echo json_encode(['success' => true, 'message' => '删除成功']);
exit;