<?php 

include './sc.php';

if ($active_ticket != "无") {
    echo "你已有工单在处理中!";
    exit;
}

// 检查必需字段
$required_fields = ['title', 'priority', 'related_product', 'msg'];
foreach ($required_fields as $field) {
    if (empty($_POST[$field])) {
        echo "缺少必要的数据: " . htmlspecialchars($field, ENT_QUOTES, 'UTF-8');
        exit;
    }
}

$title = $_POST['title'];
$priority = $_POST['priority'];
$related_product = $_POST['related_product'];
$msg = $_POST['msg'];

// 对输入进行 HTML 转义
$title = htmlspecialchars($title, ENT_QUOTES, 'UTF-8');
$priority = htmlspecialchars($priority, ENT_QUOTES, 'UTF-8');
$related_product = htmlspecialchars($related_product, ENT_QUOTES, 'UTF-8');
$msg = htmlspecialchars($msg, ENT_QUOTES, 'UTF-8');

// 检查字符串长度
$title_c = mb_strlen($title, 'UTF-8');
$msg_c = mb_strlen($msg, 'UTF-8');

if ($title_c > 30 || $msg_c > 512) {
    echo "数据不规范!";
    exit;
}

// 验证 priority 是否为低、中、高
$valid_priorities = ['低', '中', '高'];
if (!in_array($priority, $valid_priorities)) {
    echo "优先级必须是低、中或高!";
    exit;
}

// 验证 related_product 是否在指定的文件中
$related_products = file('./related_product.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (!in_array($related_product, $related_products)) {
    echo "相关产品不在可用列表中!";
    exit;
}



die("不要发你这个破工单<br>免费产品不支持工单功能");



// 获取当前时间并格式化
$time = date('Y-m-d H:i:s');

$main = '{
  "ticket": {
    "title": "测试工单",
    "created_at": "0000-00-00-00-00-00",
    "priority": "高",
    "last_reply_time": "0000-00-00-00-00-00",
    "related_product": "无",
    "status": "待接单",
    "conversation": [
      {
        "responder": "Fuxsto Host",
        "role": "admin",
        "reply_time": "'.$time.'",
        "reply_content": "我们已经收到了你的工单,我们会尽快的安排人员来处理!"
      }
    ]
  }
}';

// 解码 JSON 字符串
$data = json_decode($main, true);

// 添加新的对话到头部
$new_conversation_head = [
    "responder" => $user,
    "role" => "user",
    "reply_time" => $time,
    "reply_content" => $msg
];

$data['ticket']['title'] = $title;
$data['ticket']['created_at'] = $time;
$data['ticket']['last_reply_time'] = $time;
$data['ticket']['priority'] = $priority;
$data['ticket']['related_product'] = $related_product;

array_unshift($data['ticket']['conversation'], $new_conversation_head);

// 编码为 JSON 字符串
$main = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

// 定义要检查的文件路径
$filename = './me/' . $user . '/' . $pass . '/ticket.json'; // 目录路径
@file_put_contents($filename, $main);

$filename = './admin.txt';
if (file_exists($filename)) {
    $file = fopen($filename, 'r');
    if ($file) {
        while (($line = fgets($file)) !== false) {
            $qq = trim($line); // 去除行末的换行符和空格
            if (!empty($qq)) {
                sendMail($qq . '@qq.com', '#Fuxsto Admin 工单提醒!', "<h2>尊敬的管理员</h2><br>有工单等待处理!");
            }
        }
        fclose($file);
    } else {
        //echo "无法打开文件.";
    }
} else {
    //echo "文件不存在.";
}


echo '工单提交啦~~<meta http-equiv="refresh" content="2;url=./ticket.fx">';
?>
