<?php
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/wechat_config.php';

// 验证服务器有效性（首次配置时使用）
if (isset($_GET['echostr'])) {
    $signature = $_GET['signature'];
    $timestamp = $_GET['timestamp'];
    $nonce = $_GET['nonce'];
    $echostr = $_GET['echostr'];
    
    $tmpArr = array(WECHAT_TOKEN, $timestamp, $nonce);
    sort($tmpArr, SORT_STRING);
    $tmpStr = sha1(implode($tmpArr));
    
    if ($tmpStr == $signature) {
        echo $echostr;
    }
    exit;
}

// 处理用户消息
$postStr = file_get_contents('php://input');
if (empty($postStr)) {
    exit;
}

$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$fromUser = $postObj->FromUserName;
$msgType = $postObj->MsgType;
$content = trim($postObj->Content ?? '');

// 用户发送「授权登录」或「auth」获取验证码
if ($msgType == 'text' && ($content == '授权登录' || $content == 'auth' || $content == '登录')) {
    $code = sprintf("%06d", mt_rand(0, 999999));
    $expired_at = date('Y-m-d H:i:s', strtotime('+5 minutes'));
    
    // 保存验证码到数据库
    $db->query("REPLACE INTO email_verify_codes (email, code, type, expired_at) 
                VALUES ('$fromUser', '$code', 'wechat', '$expired_at')");
    
    $replyText = "<xml>
                    <ToUserName><![CDATA[$fromUser]]></ToUserName>
                    <FromUserName><![CDATA[{$postObj->ToUserName}]]></FromUserName>
                    <CreateTime>" . time() . "</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[【登录验证码】\n\n您的验证码是：$code\n\n验证码5分钟内有效，请在网站输入完成登录。]]></Content>
                  </xml>";
    echo $replyText;
    exit;
}

// 用户关注事件
if ($msgType == 'event' && $postObj->Event == 'subscribe') {
    $replyText = "<xml>
                    <ToUserName><![CDATA[$fromUser]]></ToUserName>
                    <FromUserName><![CDATA[{$postObj->ToUserName}]]></FromUserName>
                    <CreateTime>" . time() . "</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[欢迎关注！\n\n发送「授权登录」即可获取登录验证码。]]></Content>
                  </xml>";
    echo $replyText;
    exit;
}

// 默认回复
if ($msgType == 'text') {
    $replyText = "<xml>
                    <ToUserName><![CDATA[$fromUser]]></ToUserName>
                    <FromUserName><![CDATA[{$postObj->ToUserName}]]></FromUserName>
                    <CreateTime>" . time() . "</CreateTime>
                    <MsgType><![CDATA[text]]></MsgType>
                    <Content><![CDATA[发送「授权登录」获取登录验证码]]></Content>
                  </xml>";
    echo $replyText;
    exit;
}