<?php
/**
 * 微信客服消息接收接口
 * 用于接收微信客服消息，并存储到数据库中
 */

// 微信配置
$wechat_config = [
    'token' => 'your_token_here', // 需与微信后台配置一致
    'encodingAESKey' => '', // 消息加密密钥（可选）
    'appId' => '', // 微信AppID（可选）
];

// 获取配置
$config_file = __DIR__ . '/config.json';
if (file_exists($config_file)) {
    $saved_config = json_decode(file_get_contents($config_file), true);
    if ($saved_config) {
        $wechat_config = array_merge($wechat_config, $saved_config);
    }
}

// 验证微信服务器
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $signature = $_GET['signature'] ?? '';
    $timestamp = $_GET['timestamp'] ?? '';
    $nonce = $_GET['nonce'] ?? '';
    $echostr = $_GET['echostr'] ?? '';
    
    // 验证签名
    $tmpArr = [$wechat_config['token'], $timestamp, $nonce];
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode($tmpArr);
    $tmpStr = sha1($tmpStr);
    
    if ($tmpStr == $signature) {
        echo $echostr;
        exit;
    } else {
        echo 'signature verification failed';
        exit;
    }
}

// 接收微信消息（POST）
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $postData = file_get_contents('php://input');
    
    if (!$postData) {
        echo 'no data';
        exit;
    }
    
    // 解析XML
    $message = simplexml_load_string($postData, 'SimpleXMLElement', LIBXML_NOCDATA);
    
    if (!$message) {
        echo 'invalid xml';
        exit;
    }
    
    // 存储消息到数据库
    try {
        require_once __DIR__ . '/../config/database.php';
        
        $openid = (string)$message->FromUserName;
        $msgType = (string)$message->MsgType;
        $content = '';
        $msgId = (string)$message->MsgId;
        
        if ($msgType == 'text') {
            $content = (string)$message->Content;
        } elseif ($msgType == 'image') {
            $content = (string)$message->PicUrl;
        } elseif ($msgType == 'voice') {
            $content = (string)$message->Recognition;
        }
        
        // 检查是否已存在
        $check = db_query_one("SELECT `id` FROM `wechat_messages` WHERE `msg_id`=?", [$msgId]);
        
        if (!$check) {
            db_exec(
                "INSERT INTO `wechat_messages` (`openid`, `msg_type`, `content`, `msg_id`, `raw_data`) VALUES (?, ?, ?, ?, ?)",
                [$openid, $msgType, $content, $msgId, $postData]
            );
        }
        
        // 自动回复
        $reply = get_auto_reply($content);
        if ($reply) {
            echo build_text_response($message, $reply);
        } else {
            // 转人工客服
            echo build_transfer_customer_service($message);
        }
        
    } catch (Exception $e) {
        echo 'error: ' . $e->getMessage();
    }
    
    exit;
}

/**
 * 获取自动回复
 */
function get_auto_reply($keyword) {
    try {
        $rule = db_query_one("SELECT `reply_content` FROM `wechat_rules` WHERE `keyword`=? AND `status`=1", [$keyword]);
        return $rule ? $rule['reply_content'] : '';
    } catch (Exception $e) {
        return '';
    }
}

/**
 * 构建文本回复
 */
function build_text_response($message, $content) {
    $xml = '<xml>';
    $xml .= '<ToUserName><![CDATA[' . $message->FromUserName . ']]></ToUserName>';
    $xml .= '<FromUserName><![CDATA[' . $message->ToUserName . ']]></FromUserName>';
    $xml .= '<CreateTime>' . time() . '</CreateTime>';
    $xml .= '<MsgType><![CDATA[text]]></MsgType>';
    $xml .= '<Content><![CDATA[' . $content . ']]></Content>';
    $xml .= '</xml>';
    
    return $xml;
}

/**
 * 转人工客服
 */
function build_transfer_customer_service($message) {
    $xml = '<xml>';
    $xml .= '<ToUserName><![CDATA[' . $message->FromUserName . ']]></ToUserName>';
    $xml .= '<FromUserName><![CDATA[' . $message->ToUserName . ']]></FromUserName>';
    $xml .= '<CreateTime>' . time() . '</CreateTime>';
    $xml .= '<MsgType><![CDATA[transfer_customer_service]]></MsgType>';
    $xml .= '</xml>';
    
    return $xml;
}
