<?php
require_once '../../config.php';

error_reporting(E_ALL);
ini_set('display_errors', 1);

// ========== 支持两种模式 ==========
$is_temp_user = isset($_SESSION['temp_oauth_user']) && !empty($_SESSION['temp_oauth_user']);
$is_existing_user = isset($_SESSION['need_change_password']) && $_SESSION['need_change_password'] === true;

if (!$is_temp_user && !$is_existing_user) {
    header('Location: ' . SITE_URL . 'admin.php');
    exit;
}

$temp_user = null;
$user = null;

if ($is_temp_user) {
    $temp_user = $_SESSION['temp_oauth_user'];
} else {
    $user_id = $_SESSION['temp_user_id'];
    $user = $db->fetchOne("SELECT * FROM users WHERE id = $user_id");
    if (!$user) {
        unset($_SESSION['need_change_password']);
        header('Location: ' . SITE_URL . 'modules/home/login.php');
        exit;
    }
}

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $real_email = trim($_POST['email'] ?? '');
    
    if (strlen($password) < 6) {
        $error = '密码长度至少6位';
    } elseif ($password !== $confirm_password) {
        $error = '两次输入的密码不一致';
    } elseif (empty($real_email)) {
        $error = '请输入邮箱';
    } elseif (!filter_var($real_email, FILTER_VALIDATE_EMAIL)) {
        $error = '邮箱格式不正确';
    } else {
        $hashed = password_hash($password, PASSWORD_DEFAULT);
        
        if ($is_temp_user) {
            // 检查邮箱是否已被占用
            $email_check = $db->fetchOne("SELECT id FROM users WHERE email = '$real_email'");
            if ($email_check) {
                $error = '该邮箱已被其他用户使用';
            } else {
                // 转义变量
                $username = $db->escape($temp_user['username']);
                $email = $db->escape($real_email);
                $avatar = $db->escape($temp_user['avatar']);
                
                if ($temp_user['oauth_type'] == 'qq') {
                    $openid = $db->escape($temp_user['openid']);
                    $nickname = $db->escape($temp_user['nickname']);
                    
                    $db->query("INSERT INTO users (username, password, email, union_id, union_type, avatar_url, email_verified, role, is_oauth_user, need_change_password) 
                                VALUES ('$username', '$hashed', '$email', '$openid', 'qq', '$avatar', 1, 'user', 1, 0)");
                    $user_id = $db->insertId();
                    
                    $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                                VALUES ($user_id, 'qq', '$openid', '$nickname', '$avatar')");
                                    
                } elseif ($temp_user['oauth_type'] == 'gitee') {
                    $gitee_id = $db->escape($temp_user['gitee_id']);
                    $gitee_name = $db->escape($temp_user['gitee_name']);
                    $nickname = $db->escape($temp_user['nickname']);
                    
                    $db->query("INSERT INTO users (username, password, email, gitee_id, gitee_name, avatar_url, email_verified, role, is_oauth_user, need_change_password) 
                                VALUES ('$username', '$hashed', '$email', '$gitee_id', '$gitee_name', '$avatar', 1, 'user', 1, 0)");
                    $user_id = $db->insertId();
                    
                    $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                                VALUES ($user_id, 'gitee', '$gitee_id', '$nickname', '$avatar')");
                                        
                } elseif ($temp_user['oauth_type'] == 'union') {
                    $union_id = $db->escape($temp_user['union_id']);
                    $union_type = $db->escape($temp_user['union_type']);
                    $nickname = $db->escape($temp_user['nickname']);
                    
                    $db->query("INSERT INTO users (username, password, email, union_id, union_type, avatar_url, email_verified, role, is_oauth_user, need_change_password) 
                                VALUES ('$username', '$hashed', '$email', '$union_id', '$union_type', '$avatar', 1, 'user', 1, 0)");
                    $user_id = $db->insertId();
                    
                    $db->query("INSERT INTO user_oauth_bindings (user_id, oauth_type, openid, nickname, avatar) 
                                VALUES ($user_id, '$union_type', '$union_id', '$nickname', '$avatar')");
                }
                
                // 自动登录
                unset($_SESSION['temp_oauth_user']);
                $_SESSION['user_id'] = $user_id;
                $_SESSION['username'] = $temp_user['username'];
                $_SESSION['role'] = 'user';
                
                header('Location: ' . SITE_URL . 'admin.php');
                exit;
            }
        } else {
            // 已有用户：更新密码和邮箱
            $db->query("UPDATE users SET password = '$hashed', need_change_password = 0, email = '$real_email' WHERE id = $user_id");
            
            unset($_SESSION['need_change_password']);
            $_SESSION['user_id'] = $user_id;
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role'];
            
            header('Location: ' . SITE_URL . 'admin.php');
            exit;
        }
    }
}

$site_name = getSiteConfig('site_name') ?? '麟泓授权系统';
$display_username = $is_temp_user ? $temp_user['username'] : $user['username'];
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>设置密码 - <?php echo htmlspecialchars($site_name); ?></title>
    <link rel="stylesheet" href="/assets/css/style.css">
    <link rel="stylesheet" href="/assets/css/dark.css" id="dark-theme" disabled>
    <style>
        body {
            background: linear-gradient(135deg, #667eea, #764ba2);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        .card {
            max-width: 450px;
            width: 100%;
            background: white;
            border-radius: 24px;
            padding: 40px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.2);
        }
        .card h2 {
            text-align: center;
            margin-bottom: 10px;
            color: #333;
        }
        .card p {
            text-align: center;
            color: #666;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: #333;
        }
        .form-group input {
            width: 100%;
            padding: 12px 16px;
            border: 1px solid #ddd;
            border-radius: 12px;
            font-size: 14px;
            transition: all 0.2s;
        }
        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102,126,234,0.1);
        }
        .btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s;
        }
        .btn:hover {
            transform: translateY(-2px);
        }
        .alert {
            padding: 12px 16px;
            border-radius: 12px;
            margin-bottom: 20px;
        }
        .alert-error {
            background: #fee2e2;
            color: #991b1b;
            border: 1px solid #fecaca;
        }
        .tip {
            margin-top: 20px;
            text-align: center;
            font-size: 12px;
            color: #999;
        }
        .username-display {
            background: #f5f5f5;
            padding: 10px;
            border-radius: 8px;
            text-align: center;
            margin-bottom: 20px;
            color: #666;
        }
        .oauth-badge {
            display: inline-block;
            background: #667eea;
            color: white;
            padding: 2px 10px;
            border-radius: 20px;
            font-size: 12px;
            margin-left: 8px;
        }
        .email-hint {
            font-size: 12px;
            color: #999;
            margin-top: 5px;
        }
    </style>
</head>
<body>
<div class="card">
    <h2>🔐 完善账号信息</h2>
    <p>请设置密码和邮箱，用于登录和接收通知</p>
    
    <?php if ($error): ?>
        <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
    <?php endif; ?>
    
    <div class="username-display">
        用户名：<strong><?php echo htmlspecialchars($display_username); ?></strong>
        <?php if ($is_temp_user && isset($temp_user['oauth_type'])): ?>
            <span class="oauth-badge">
                <?php 
                $type_names = [
                    'qq' => 'QQ登录',
                    'gitee' => 'Gitee登录',
                    'union' => '快捷登录'
                ];
                echo $type_names[$temp_user['oauth_type']] ?? '第三方登录';
                ?>
            </span>
        <?php endif; ?>
    </div>
    
    <form method="POST">
        <div class="form-group">
            <label>邮箱</label>
            <input type="email" name="email" placeholder="请输入您的真实邮箱（用于接收通知）" required autofocus>
            <div class="email-hint">💡 设置后可用于登录和接收订单、充值等通知</div>
        </div>
        <div class="form-group">
            <label>密码</label>
            <input type="password" name="password" placeholder="至少6位" required>
        </div>
        <div class="form-group">
            <label>确认密码</label>
            <input type="password" name="confirm_password" placeholder="请再次输入密码" required>
        </div>
        <button type="submit" class="btn">完成注册并登录</button>
    </form>
    <div class="tip">
        <p>设置后可使用邮箱+密码登录，也可继续使用第三方登录</p>
    </div>
</div>
</body>
</html>