<?php
require "../../../include/common.php";
$web_apikey = $apiCredentials['web_apikey'] ?? '';
if (!isset($_GET['apikey']) || $_GET['apikey'] !== $web_apikey) {
    echo json_encode(['code' => 401, 'data' => 'Unauthorized access.']);
    exit;
}
// 短信宝接口
$sms_url = "http://smsbao.com/sms";
$smsbao_signname = $apiCredentials["smsbao_signname"];
$sms_user = $apiCredentials["smsbao_username"];
$sms_apikey = $apiCredentials["smsbao_apikey"];

$data = json_decode(file_get_contents("php://input"), true);

if (isset($data['mobile']) && isset($data['message'])) {
    $mobile = $data['mobile'];
    $responseMessage = "";

    if (preg_match('/sendcode(\d+)/', $data['message'], $matches)) {
        $code = $matches[1];
        $responseMessage = "您的验证码是: " . $code;
    } elseif (strpos($data['message'], 'newticket') !== false) {
        $responseMessage = "您收到了新的工单";
    } elseif (strpos($data['message'], 'userreply') !== false) {
        $responseMessage = "有用户回复了您的工单";
    } elseif (strpos($data['message'], 'adminreply') !== false) {
        $responseMessage = "您的工单有了新的回复";
    } else {
        $responseMessage = "消息内容未匹配任何条件。";
    }

    $message = "【" . $smsbao_signname . "】" . $responseMessage;

    $message = mb_convert_encoding($message, "UTF-8", "auto");

    $url = $sms_url . "?u=" . $sms_user . "&p=" . $sms_apikey . "&m=" . $mobile . "&c=" . urlencode($message);

    $response = file_get_contents($url);

    if ($response === "0") {
        echo json_encode(['code' => 200, 'data' => '短信发送成功.']);
    } else {
        echo $response;
    }
} else {
    echo "缺少手机号或短信内容.";
}
