<?php
header("Content-Type: application/json; charset=utf-8");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,POST,OPTIONS");
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(json_encode(['code' => 0]));
}
session_start();
$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    echo json_encode(['code' => 401, 'msg' => '登录失效']);
    exit;
}
$loginUid = $_SESSION['user_id'];

// 数据库配置，优先本地localhost
$dbHost = '10.150.117.190';
$dbUser = 'root';
$dbPwd = 'hp93000';
$dbName = 'monitor';
$dbPort = 3306;

// 关键：连接后立刻判断是否失败
$conn = mysqli_connect($dbHost, $dbUser, $dbPwd, $dbName, $dbPort);
if (!$conn) {
    echo json_encode([
        'code' => 500,
        'msg' => '数据库连接失败：' . mysqli_connect_error() . ' 错误码：' . mysqli_connect_errno()
    ]);
    exit;
}
// 只有连接成功才执行字符集
mysqli_set_charset($conn, 'utf8mb4');

// 下面原有业务代码不变 ...
// 获取角色
$isAdmin = 0;
$r = mysqli_query($conn,"SELECT r.is_admin FROM sys_user u LEFT JOIN sys_role r ON u.role_id=r.id WHERE u.uid='$loginUid'");
if($rr = mysqli_fetch_assoc($r)) $isAdmin = intval($rr['is_admin']);
$action = $_REQUEST['action'] ?? '';
$post = json_decode(file_get_contents("php://input"),true) ?: [];

// 1、新建工单
if($action === "create"){
    $title = $post['title'] ?? '';
    $content = $post['content'] ?? '';
    $assign = $post['assign_uid'] ?? '';
    if(!$title || !$content){
        echo json_encode(['code'=>400,'msg'=>'标题和内容不能为空']);
        exit;
    }
    $sql = "INSERT INTO work_order(title,content,create_uid,assign_uid,status,create_time,update_time) VALUES (?,?,?,?,?,NOW(),NOW())";
    $stmt = mysqli_prepare($conn,$sql);
    mysqli_stmt_bind_param($stmt,'ssssi',$title,$content,$loginUid,$assign,1);
    $ok = mysqli_stmt_execute($stmt);
    if($ok) echo json_encode(['code'=>0,'msg'=>'工单提交成功']);
    else echo json_encode(['code'=>500,'msg'=>'提交失败：'.mysqli_error($conn)]);
    exit;
}

// 2、修改工单状态
if($action === "update_status"){
    $id = intval($post['id'] ?? 0);
    $status = intval($post['status'] ?? 1);
    if($id <=0){
        echo json_encode(['code'=>400,'msg'=>'工单ID错误']);
        exit;
    }
    // 权限校验：普通用户只能改自己创建/分配给自己的工单
    if($isAdmin !== 1){
        $chk = mysqli_query($conn,"SELECT id FROM work_order WHERE id=$id AND (create_uid='$loginUid' OR assign_uid='$loginUid')");
        if(mysqli_num_rows($chk) === 0){
            echo json_encode(['code'=>403,'msg'=>'无权限操作该工单']);
            exit;
        }
    }
    $sql = "UPDATE work_order SET status=?,update_time=NOW() WHERE id=?";
    $stmt = mysqli_prepare($conn,$sql);
    mysqli_stmt_bind_param($stmt,'ii',$status,$id);
    mysqli_stmt_execute($stmt);
    echo json_encode(['code'=>0,'msg'=>'状态更新成功']);
    exit;
}

// 3、管理员分发工单
if($action === "assign_order"){
    if($isAdmin !== 1){
        echo json_encode(['code'=>403,'msg'=>'仅管理员可分发工单']);
        exit;
    }
    $id = intval($post['id'] ?? 0);
    $assignUid = $post['assign_uid'] ?? '';
    $sql = "UPDATE work_order SET assign_uid=?,update_time=NOW() WHERE id=?";
    $stmt = mysqli_prepare($conn,$sql);
    mysqli_stmt_bind_param($stmt,'si',$assignUid,$id);
    mysqli_stmt_execute($stmt);
    echo json_encode(['code'=>0,'msg'=>'工单分发成功']);
    exit;
}

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