<?php
require_once 'config.php';
header('Content-Type: application/json');

// 只接受 POST 请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '请求方式错误']);
    exit;
}

// 获取参数
$code = trim($_POST['code'] ?? '');
$package_id = intval($_POST['package_id'] ?? 0);
$user_id = $_SESSION['encrypt_user_id'] ?? 0;

if (!$code) {
    echo json_encode(['success' => false, 'message' => '请输入优惠码']);
    exit;
}

if (!$package_id) {
    echo json_encode(['success' => false, 'message' => '请先选择套餐']);
    exit;
}

if (!$user_id) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

// 获取套餐价格
$package = getPackageById($package_id);
if (!$package) {
    echo json_encode(['success' => false, 'message' => '套餐不存在']);
    exit;
}

$amount = floatval($package['price']);

// 验证优惠码
$result = validateCoupon($code, $user_id, $amount);

echo json_encode($result);
?>