<?php
// 验证服务器（GET请求）
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $signature = $_GET['signature'] ?? '';
    $timestamp = $_GET['timestamp'] ?? '';
    $nonce = $_GET['nonce'] ?? '';
    $echostr = $_GET['echostr'] ?? '';
    
    $token = 'ghy200808260090';
    $arr = [$token, $timestamp, $nonce];
    sort($arr, SORT_STRING);
    $str = implode('', $arr);
    $sign = sha1($str);
    
    if ($sign === $signature) {
        echo $echostr;
    }
    exit;
}

// 接收消息
require_once __DIR__ . '/../config.php';

$postStr = file_get_contents('php://input');
if (empty($postStr)) exit;

$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUsername = (string)$postObj->FromUserName;
$toUsername = (string)$postObj->ToUserName;
$msgType = (string)$postObj->MsgType;

// 关注事件
if ($msgType === 'event' && $postObj->Event === 'subscribe') {
    replyText($fromUsername, $toUsername, "欢迎关注！\n\n发送「登录」获取登录验证码\n发送「绑定」获取绑定验证码");
    exit;
}

// 文本消息
if ($msgType !== 'text') exit;

$content = trim((string)$postObj->Content);

// 处理登录
if ($content === '登录') {
    replyText($fromUsername, $toUsername, "请在平台点击「微信验证码登录」获取验证码，然后将验证码发送给我");
    exit;
}

// 处理绑定
if ($content === '绑定') {
    replyText($fromUsername, $toUsername, "请在平台「微信绑定」页面获取验证码，然后将验证码发送给我");
    exit;
}

// 处理6位验证码
if (preg_match('/^\d{6}$/', $content)) {
    $code = $content;
    // 记录日志
    file_put_contents(__DIR__ . '/wechat-debug.log', date('Y-m-d H:i:s') . " - 收到验证码: {$code}, openid: {$fromUsername}\n", FILE_APPEND);
    // 使用全局 $db 对象
    global $db;
    
    // 先尝试匹配登录验证码
    $db->query("UPDATE wechat_login_tokens SET openid = '$fromUsername', status = 1 WHERE code = '$code' AND status = 0 AND expire_at > NOW()");
    
    if ($db->affectedRows() > 0) {
        replyText($fromUsername, $toUsername, "登录验证成功！平台将自动登录。");
        exit;
    }
    
    // 再尝试匹配绑定验证码
    $db->query("UPDATE wechat_bind_tokens SET openid = '$fromUsername', status = 1 WHERE code = '$code' AND status = 0 AND expire_at > NOW()");
    
    if ($db->affectedRows() > 0) {
        replyText($fromUsername, $toUsername, "绑定验证成功！平台将自动完成绑定。");
        exit;
    }
    
    // 都匹配不到
    replyText($fromUsername, $toUsername, "验证码错误或已过期，请刷新平台重新获取。");
    exit;
}

// 其他消息
replyText($fromUsername, $toUsername, "发送「登录」获取登录验证码\n发送「绑定」获取绑定验证码");
exit;

function replyText($to, $from, $content) {
    $time = time();
    $xml = "<xml>
<ToUserName><![CDATA[{$to}]]></ToUserName>
<FromUserName><![CDATA[{$from}]]></FromUserName>
<CreateTime>{$time}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[{$content}]]></Content>
</xml>";
    echo $xml;
    exit;
}