<?php
// ---------- 配置 ----------
$db = new PDO("mysql+pymysql://jmmoyu_user:jmmoyu_pass@127.0.0.1:3306/jmmoyu?charset=utf8mb4");
$apiId   = 23258644;
$apiHash = 'c52bbe04227330e8e8868b7e9a1d4c52';
$sessionDir = __DIR__ . '/sessions';

// ---------- 处理 POST ----------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone = $_POST['phone'] ?? '';
    $pwd   = $_POST['pwd'] ?? '';

    // 1. 验证卡密
    $stmt = $db->prepare('SELECT 1 FROM cards WHERE phone = ? AND password = ?');
    $stmt->execute([$phone,$pwd]);
    if (!$stmt->fetch()) {
        exit(json_encode(['error'=>'卡密错误']));
    }

    // 2. 检查 session 文件
    $session = $sessionDir . "/{$phone}.session";
    if (!file_exists($session)) {
        exit(json_encode(['error'=>'session 文件不存在']));
    }

    // 3. 用 Python 一次性获取验证码
    $pyCode = <<<PY
import asyncio, re, sys
from telethon import TelegramClient
client = TelegramClient('{$session}', {$apiId}, '{$apiHash}')
async def main():
    await client.start()
    code = None
    @client.on('events.NewMessage(chats=777000)')
    async def handler(e):
        nonlocal code
        m = re.search(r'(\d{5,6})', e.raw_text or '')
        if m:
            code = m.group(1)
            await client.disconnect()
    try:
        await asyncio.wait_for(client.run_until_disconnected(), timeout=15)
    except asyncio.TimeoutError:
        pass
    print(code or '')
asyncio.run(main())
PY;
    file_put_contents('/tmp/_once.py', $pyCode);
    $code = shell_exec("python3 /tmp/_once.py 2>/dev/null");
    if (!$code) {
        exit(json_encode(['error'=>'未收到验证码']));
    }
    exit(json_encode(['code'=>trim($code)]));
}
?>
<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>卡密-验证码</title></head>
<body>
<h2>请输入卡密</h2>
<form id="f">
手机号：<input name="phone" placeholder="+8613812345678" required><br>
密  码：<input type="password" name="pwd" required><br>
<button>立即获取验证码</button>
</form>
<pre id="result"></pre>

<script>
document.getElementById('f').addEventListener('submit', async (e) => {
  e.preventDefault();
  const fd = new FormData(e.target);
  const r = await fetch('', {method:'POST', body: fd});
  const j = await r.json();
  document.getElementById('result').textContent = j.error ? '❌ '+j.error : '✅ 验证码: '+j.code;
});
</script>
</body>
</html>