<?php
/**
 * 微信公众号登录回调页面
 * 接收微信授权code，获取用户信息并登录
 */
require_once __DIR__ . '/../config.php';

$db = getDB();

// 获取公众号配置
$stmt = $db->query("SELECT key_name, value FROM settings WHERE group_name = 'wechat'");
$wechatConfig = [];
foreach ($stmt->fetchAll() as $row) {
    $wechatConfig[$row['key_name']] = $row['value'];
}

$appid = $wechatConfig['wechat_appid'] ?? '';
$secret = $wechatConfig['wechat_secret'] ?? '';
$forceFollow = ($wechatConfig['wechat_force_follow'] ?? '0') === '1';
$qrcode = $wechatConfig['wechat_qrcode_url'] ?? '';

if (empty($appid) || empty($secret)) {
    die('公众号配置不完整，请联系管理员');
}

$code = $_GET['code'] ?? '';
$state = $_GET['state'] ?? '';

if (empty($code)) {
    // 没有code，可能用户拒绝授权
    header('Location: ' . SITE_URL . '/pages/login.php');
    exit;
}

// Step 1: 用code换取access_token
$tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$secret}&code={$code}&grant_type=authorization_code";
$tokenResponse = @file_get_contents($tokenUrl);
$tokenData = json_decode($tokenResponse, true);

if (!$tokenData || isset($tokenData['errcode'])) {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>登录失败</title></head><body style="font-family:sans-serif;text-align:center;padding:40px;"><h2>登录失败</h2><p>微信授权获取失败，请重试</p><a href="' . SITE_URL . '/pages/login.php" style="color:#374151;">返回登录</a></body></html>';
    exit;
}

$accessToken = $tokenData['access_token'];
$openid = $tokenData['openid'];

// Step 2: 用access_token获取用户信息
$userInfoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token={$accessToken}&openid={$openid}&lang=zh_CN";
$userInfoResponse = @file_get_contents($userInfoUrl);
$userInfo = json_decode($userInfoResponse, true);

if (!$userInfo || isset($userInfo['errcode'])) {
    echo '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>登录失败</title></head><body style="font-family:sans-serif;text-align:center;padding:40px;"><h2>登录失败</h2><p>获取用户信息失败，请重试</p><a href="' . SITE_URL . '/pages/login.php" style="color:#374151;">返回登录</a></body></html>';
    exit;
}

$wechatNickname = $userInfo['nickname'] ?? '';
$wechatAvatar = $userInfo['headimgurl'] ?? '';

// Step 3: 查找或创建用户
$stmt = $db->prepare("SELECT * FROM users WHERE wechat_openid = ?");
$stmt->execute([$openid]);
$existingUser = $stmt->fetch();

if ($existingUser) {
    // 已有用户，更新微信信息
    $stmt = $db->prepare("UPDATE users SET wechat_nickname = ?, wechat_avatar = ?, avatar = COALESCE(avatar, ?) WHERE id = ?");
    $stmt->execute([$wechatNickname, $wechatAvatar, $wechatAvatar, $existingUser['id']]);
    $_SESSION['user_id'] = $existingUser['id'];
} else {
    // 新用户，创建
    $username = 'wx_' . substr($openid, -8);
    $stmt = $db->prepare("INSERT INTO users (username, password, real_name, avatar, wechat_openid, wechat_nickname, wechat_avatar) VALUES (?, '', ?, ?, ?, ?, ?)");
    $stmt->execute([$username, $wechatNickname, $wechatAvatar, $openid, $wechatNickname, $wechatAvatar]);
    $_SESSION['user_id'] = $db->lastInsertId();
}

// Step 4: 如果开启了强关模式，需检查是否关注公众号
if ($forceFollow) {
    // 获取公众号access_token（不同于网页授权的token）
    $cgiTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$secret}";
    $cgiTokenResponse = @file_get_contents($cgiTokenUrl);
    $cgiTokenData = json_decode($cgiTokenResponse, true);

    if ($cgiTokenData && !isset($cgiTokenData['errcode'])) {
        $cgiAccessToken = $cgiTokenData['access_token'];
        // 检查用户是否关注公众号
        $followUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token={$cgiAccessToken}&openid={$openid}&lang=zh_CN";
        $followResponse = @file_get_contents($followUrl);
        $followData = json_decode($followResponse, true);

        if ($followData && isset($followData['subscribe'])) {
            $isFollowed = $followData['subscribe'] == 1;

            if ($isFollowed) {
                // 已关注，更新状态
                $stmt = $db->prepare("UPDATE users SET is_follow_wechat = 1 WHERE wechat_openid = ?");
                $stmt->execute([$openid]);
            } else {
                // 未关注，显示强关遮罩页面
                ?>
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>关注公众号</title>
                    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css">
                    <style>
                        * { margin: 0; padding: 0; box-sizing: border-box; }
                        body {
                            font-family: -apple-system, sans-serif;
                            background: rgba(0,0,0,0.6);
                            min-height: 100vh;
                            display: flex;
                            align-items: center;
                            justify-content: center;
                        }
                        .follow-modal {
                            background: white;
                            border-radius: 16px;
                            padding: 32px 24px;
                            text-align: center;
                            max-width: 340px;
                            width: 90%;
                        }
                        .follow-title {
                            font-size: 18px;
                            font-weight: 600;
                            color: #1f2937;
                            margin-bottom: 12px;
                        }
                        .follow-desc {
                            font-size: 14px;
                            color: #6b7280;
                            margin-bottom: 24px;
                        }
                        .follow-qrcode {
                            width: 200px;
                            height: 200px;
                            margin: 0 auto 16px;
                            background: #f3f4f6;
                            border-radius: 8px;
                            overflow: hidden;
                        }
                        .follow-qrcode img { width: 100%; height: 100%; object-fit: contain; }
                        .follow-hint {
                            font-size: 12px;
                            color: #9ca3af;
                            margin-bottom: 24px;
                        }
                        .follow-btn {
                            display: inline-block;
                            padding: 12px 24px;
                            background: #07c160;
                            color: white;
                            border-radius: 8px;
                            font-size: 14px;
                            cursor: pointer;
                        }
                    </style>
                </head>
                <body>
                    <div class="follow-modal">
                        <div class="follow-title">请先关注公众号</div>
                        <div class="follow-desc">为了更好的服务体验，请先关注我们的公众号完成绑定</div>
                        <?php if ($qrcode): ?>
                        <div class="follow-qrcode">
                            <img src="<?php echo htmlspecialchars($qrcode); ?>" alt="公众号二维码">
                        </div>
                        <?php else: ?>
                        <div class="follow-desc">请在微信中搜索并关注我们的公众号</div>
                        <?php endif; ?>
                        <div class="follow-hint">长按识别二维码关注后，点击下方按钮继续</div>
                        <a class="follow-btn" href="<?php echo SITE_URL; ?>/pages/wechat-callback.php?code=<?php echo urlencode($code); ?>&state=<?php echo urlencode($state); ?>&refollow=1">
                            我已关注，继续登录
                        </a>
                    </div>
                </body>
                </html>
                <?php
                exit;
            }
        }
    }
}

// 登录成功，重定向到首页
header('Location: ' . SITE_URL . '/index.php');
exit;
