<?php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(json_encode(['code' => 0, 'msg' => 'ok']));
}

// 数据库配置
$dbHost = '127.0.0.1';
$dbUser = 'root';
$dbPwd = 'hp93000';
$dbName = 'monitor';

session_start();
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    echo json_encode(['code' => 401, 'msg' => '登录失效，请重新登录']);
    exit;
}
$uid = $_SESSION['user_id'];

$conn = mysqli_connect($dbHost, $dbUser, $dbPwd, $dbName);
if (!$conn) {
    echo json_encode(['code' => 500, 'msg' => '数据库连接失败:' . mysqli_connect_error()]);
    exit;
}
mysqli_set_charset($conn, 'utf8mb4');

$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

// 获取当前用户订阅配置
if ($action === 'get_subscribe') {
    $sql = "SELECT * FROM alert_subscribe WHERE uid = ? LIMIT 1";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 's', $uid);
    mysqli_stmt_execute($stmt);
    $res = mysqli_stmt_get_result($stmt);
    $data = mysqli_fetch_assoc($res);
    if (empty($data)) {
        $data = [
            'severity' => '',
            'instance' => '',
            'alertname' => '',
            'dingtalk_webhook' => '',
            'wecom_webhook' => '',
            'mail_receiver' => '',
            'enable' => 0
        ];
    }
    echo json_encode(['code' => 0, 'msg' => 'ok', 'data' => $data], JSON_UNESCAPED_UNICODE);
    exit;
}

// 保存/更新订阅配置
if ($action === 'save_subscribe') {
    $post = json_decode(file_get_contents('php://input'), true);
    $severity = $post['severity'] ?? '';
    $instance = $post['instance'] ?? '';
    $alertname = $post['alertname'] ?? '';
    $dingtalk = $post['dingtalk_webhook'] ?? '';
    $wecom = $post['wecom_webhook'] ?? '';
    $mail = $post['mail_receiver'] ?? '';
    $enable = intval($post['enable'] ?? 0);

    $check = mysqli_query($conn, "SELECT id FROM alert_subscribe WHERE uid = '$uid' LIMIT 1");
    if (mysqli_num_rows($check) > 0) {
        $sql = "UPDATE alert_subscribe SET severity=?,instance=?,alertname=?,dingtalk_webhook=?,wecom_webhook=?,mail_receiver=?,enable=? WHERE uid=?";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, 'ssssssis', $severity, $instance, $alertname, $dingtalk, $wecom, $mail, $enable, $uid);
    } else {
        $sql = "INSERT INTO alert_subscribe(uid,severity,instance,alertname,dingtalk_webhook,wecom_webhook,mail_receiver,enable) VALUES (?,?,?,?,?,?,?,?)";
        $stmt = mysqli_prepare($conn, $sql);
        mysqli_stmt_bind_param($stmt, 'ssssssss', $uid, $severity, $instance, $alertname, $dingtalk, $wecom, $mail, $enable);
    }
    $ok = mysqli_stmt_execute($stmt);
    if ($ok) {
        echo json_encode(['code' => 0, 'msg' => '订阅配置保存成功'], JSON_UNESCAPED_UNICODE);
    } else {
        echo json_encode(['code' => 500, 'msg' => '保存失败:' . mysqli_error($conn)], JSON_UNESCAPED_UNICODE);
    }
    exit;
}

echo json_encode(['code' => 400, 'msg' => '无效操作']);
mysqli_close($conn);
exit;
?>
