<?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 = '10.150.117.190';
$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'] : '';

// 1、获取当前用户订阅配置
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;
}

// 2、保存/更新订阅配置
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;
}

// 3、分页查询推送日志
if ($action === 'list_push_log') {
    $page = isset($_REQUEST['page']) ? intval($_REQUEST['page']) : 1;
    $pageSize = isset($_REQUEST['page_size']) ? intval($_REQUEST['page_size']) : 10;
    $offset = ($page - 1) * $pageSize;

    // 总条数
    $cntSql = "SELECT COUNT(*) as total FROM alert_push_log WHERE uid = ?";
    $stmtCnt = mysqli_prepare($conn, $cntSql);
    mysqli_stmt_bind_param($stmtCnt, 's', $uid);
    mysqli_stmt_execute($stmtCnt);
    $cntRow = mysqli_fetch_assoc(mysqli_stmt_get_result($stmtCnt));
    $total = $cntRow['total'];

    // 分页数据
    $sql = "SELECT * FROM alert_push_log WHERE uid = ? ORDER BY push_time DESC LIMIT ?,?";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt, 'sii', $uid, $offset, $pageSize);
    mysqli_stmt_execute($stmt);
    $res = mysqli_stmt_get_result($stmt);
    $list = [];
    while ($row = mysqli_fetch_assoc($res)) {
        $list[] = $row;
    }
    echo json_encode([
        'code' => 0,
        'msg' => 'ok',
        'data' => [
            'list' => $list,
            'page' => $page,
            'page_size' => $pageSize,
            'total' => $total,
            'pages' => ceil($total / $pageSize)
        ]
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

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