<?php
ob_start(); // 输出缓冲,误改
session_name('user_session');
session_start();
require '../include/common.php';

// 确保用户已登录
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$userId = $_SESSION['user_id']; // 当前用户 ID
$apikey = $apiCredentials['web_apikey'];
// 获取用户信息
$stmt = $pdo->prepare("SELECT * FROM " . table('users') . " WHERE id = :id");
$stmt->execute(['id' => $userId]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// 检查用户信息是否获取成功
if (!$user) {
    echo "未找到该用户，或用户信息加载失败。";
    exit();
}

// 检查实名状态
$isRealNameVerified = $user['real_name_status'] == 1;
//检查用户的API权限
$isApiAllowed = $user['api_use_status'] and $currentSettings['user_api_status'] == 1;
// 处理POST请求
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 处理实名认证更新
    if (isset($_POST['real_name'])) {
        $newRealName = $_POST['real_name'] ?? '';
        $newIdCard = $_POST['id_card'] ?? '';
        $newTruePhone = $_POST['true_phone'] ?? '';

        // 验证身份证号码和真实手机号不能为空
        if (empty($newIdCard) || empty($newTruePhone)) {
            echo "<script>alert('身份证号码和真实手机号不能为空！');</script>";
            exit();
        }

        // 准备要发送的数据
        $data = [
            'IdCard' => $newIdCard,
            'Name' => $newRealName,
            'Phone' => $newTruePhone
        ];

        // 获取当前域名和前缀
        $currentHost = $_SERVER['HTTP_HOST'];
        $currentScheme = $_SERVER['REQUEST_SCHEME'];
        $domain = $currentScheme . '://' . $currentHost;
        $realname_interface = $currentSettings['realname_interface'];
        $url = $domain . '/other/realname/' . $realname_interface . '/index.php?apikey=' . $apikey;

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // 以 JSON 格式发送数据
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json'
        ]);

        // 执行请求并获取响应
        $response = curl_exec($ch);

        // 检查请求是否成功
        if ($response === false) {
            echo "<script>alert('请求失败: " . curl_error($ch) . "');</script>";
            curl_close($ch);
            exit();
        }

        // 关闭 cURL 会话
        curl_close($ch);

        // 解析 JSON 响应
        $responseData = json_decode($response, true);

        // 检查返回的状态
        if (isset($responseData['Result']) && $responseData['Result'] === "0") { // 根据新的响应格式检查
            // 更新 real_name, id_card 和 true_phone
            $updateRealNameStmt = $pdo->prepare("UPDATE " . table('users') . " SET real_name = :real_name, id_card = :id_card, true_phone = :true_phone, real_name_status = 1 WHERE id = :id");
            $updateRealNameStmt->execute([
                'real_name' => $newRealName,
                'id_card' => $newIdCard,
                'true_phone' => $newTruePhone,
                'id' => $userId
            ]);
            echo "<script>alert('实名认证更新成功！');</script>";
            // 更新成功后重定向到 /profile.php?realname
            header("Location: profile.php?realname");
            exit();
        } else {
            // 返回的状态不为 0，显示错误信息
            echo "<script>alert('实名认证更新失败: " . ($responseData['Description'] ?? '未知错误') . "');</script>";
        }

    } elseif (isset($_POST['spdnsid'])) {
        // 处理SPDNS更新
        $newSpdnsid = $_POST['spdnsid'] ?? '';
        $newSpdnskey = $_POST['spdnskey'] ?? '';
        // 更新 spdnsid 和 spdnskey
        $updateApiStmt = $pdo->prepare("UPDATE " . table('users') . " SET spdnsid = :spdnsid, spdnskey = :spdnskey WHERE id = :id");
        $updateApiStmt->execute([
            'spdnsid' => $newSpdnsid,
            'spdnskey' => $newSpdnskey,
            'id' => $userId
        ]);

        // 更新成功后设置状态标志并重定向
        echo "<script>alert('SPDNS ID和Key更新成功！');</script>";
        header("Location: profile.php?apikey");
        exit();



    } elseif (isset($_POST['qq'])) {
        // 个人信息修改处理
        $newName = $_POST['name'] ?? '';
        $newQQ = $_POST['qq'] ?? '';

        // 验证QQ、昵称不能为空
        if (empty($newQQ) || empty($newName)) {
            echo "<script>alert('昵称、QQ不能为空！');</script>";
            exit();
        }

        // 更新用户信息
        try {
            $updateUserStmt = $pdo->prepare("UPDATE " . table('users') . " SET name = :name, qq = :qq WHERE id = :id");
            $updateUserStmt->execute([
                'name' => $newName,
                'qq' => $newQQ,
                'id' => $userId
            ]);
            echo "<script>alert('信息更新成功！');</script>";
            header("Location: profile.php?message=update_success");
            exit();
        } catch (PDOException $e) {
            echo "<script>alert('更新失败：" . $e->getMessage() . "');</script>";
        }
    }
}
?>
<?php
if (isset($_SESSION['user'])) {
    // 获取当前用户类型和openid
    $type = $_SESSION['user']['type'];
    $openid = $_SESSION['user']['social_uid'];

    // 假设您有个函数用于更新用户信息，例如 updateUser()
    try {
        // 根据$type判断并更新相应的用户字段
        if ($type === 'qq') {
            // 更新QQ UID，并获取返回结果
            $result = updateUser($userId, ['qq_uid' => $openid]);
            $openid = null;
        } elseif ($type === 'wx') {
            // 更新微信 UID，并获取返回结果
            $result = updateUser($userId, ['wx_uid' => $openid]);
            $openid = null;
        } elseif ($type === 'alipay') {
            // 更新支付宝 UID，并获取返回结果
            $result = updateUser($userId, ['alipay_uid' => $openid]);
            $openid = null;
        }

        // 检查返回结果中的 $code 是否为 0
        if (isset($result['code']) && $result['code'] === 0) {
            echo "<script>alert('绑定成功！');</script>";
        }
    } catch (Exception $e) {
        echo "<script>alert('更新失败：" . $e->getMessage() . "');</script>";
    }
}
?>



<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>更新用户信息</title>
    <script src="../assets/js/jquery.min.js"></script>
    <link rel="stylesheet" href="../assets/css/bootstrap.min.css">
</head>

<body class="bg-light">
    <?php include 'header.php'; ?>
    <div class="main-content">
        <div class="page-content">
            <div class="container-fluid">
                <?php if (isset($_GET['message'])): ?>
                    <?php if ($_GET['message'] === 'update_success'): ?>
                        <div class="alert alert-success" role="alert">
                            资料更新成功！
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
                <?php
                if (isset($_GET['verify'])) {
                    if ($_GET['verify'] === 'email') {
                        // 处理邮箱修改逻辑
                        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                            $newEmail = $_POST['new_email'] ?? '';
                            $verificationCode = $_POST['verification_code'] ?? '';
                            // 验证验证码
                            if (isset($_SESSION['verification_code']) && $_SESSION['verification_code'] == $verificationCode) {
                                // 更新邮箱
                                $updateEmailStmt = $pdo->prepare("UPDATE " . table('users') . " SET email = :email WHERE id = :id");
                                $updateEmailStmt->execute(['email' => $newEmail, 'id' => $userId]);
                                $_SESSION['alert_message'] = '邮箱更新成功！';
                                header("Location: profile.php?message=update_success");
                                exit();
                            } else {
                                $_SESSION['alert_message'] = '验证码不正确！';
                                header("Location: profile.php?verify=email");
                                exit();
                            }
                        }
                        $secretKey = bin2hex(random_bytes(16));
                        $_SESSION['secret_key'] = $secretKey;
                        ?>
                        <h1 class="text-center">更新邮箱</h1>
                        <form method="post" action="profile.php?verify=email">
                            <div class="mb-3">
                                <label for="email" class="form-label">当前邮箱:</label>
                                <input type="email" class="form-control"
                                    value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" readonly>
                            </div>
                            <div class="mb-3 row align-items-center">
                                <label for="new_email" class="form-label">新邮箱:</label>
                                <div class="col-12 col-sm-12">
                                    <input type="email" class="form-control" name="new_email" id="new_email" required>
                                </div>
                                <div style="margin-top: 1rem;" class="col-12 col-sm-12">
                                    <button type="button" class="btn btn-secondary col-12" onclick="sendVerificationCode()"
                                        style="white-space: nowrap;">发送验证码</button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="verification_code" class="form-label">验证码:</label>
                                <input type="text" class="form-control" name="verification_code" id="verification_code"
                                    required>
                            </div>
                            <button type="submit" class="btn btn-primary col-12">确认更新</button>
                        </form>

                        <script>
                            function sendVerificationCode() {
                                // 使用 jQuery 获取新邮箱地址的值
                                var newEmail = $('#new_email').val();

                                if (!newEmail) {
                                    alert('请填写新邮箱地址。');
                                    return;
                                }

                                var secretKey = "<?php echo $secretKey; ?>";
                                var dataToSend = {
                                    email: newEmail,
                                    secret_key: secretKey
                                };

                                // 禁用按钮并改变样式
                                var button = document.querySelector("button[onclick='sendVerificationCode()']");
                                button.disabled = true;
                                button.classList.add('btn-secondary');
                                button.classList.remove('btn-primary');
                                button.innerText = '发送中...';

                                // AJAX 请求发送验证码
                                $.ajax({
                                    url: 'ajax.php', // 确保 AJAX 请求路径正确
                                    type: 'POST',
                                    contentType: 'application/json',
                                    data: JSON.stringify(dataToSend),
                                    dataType: 'json',
                                    success: function (response) {
                                        if (response.success) {
                                            alert(response.message); // 显示发送状态
                                        } else {
                                            alert('发送验证码失败: ' + response.message); // 显示错误信息
                                        }
                                        // 重新启用按钮
                                        button.disabled = false;

                                        button.classList.remove('btn-secondary');
                                        button.classList.add('btn-primary');
                                        button.innerText = '发送验证码';
                                    },
                                    error: function () {
                                        alert('请求发生错误。');
                                        // 重新启用按钮
                                        button.disabled = false;
                                        button.classList.remove('btn-secondary');
                                        button.classList.add('btn-primary');
                                        button.innerText = '发送验证码';
                                    }
                                });

                                // 在发送 AJAX 请求之前输出 data 到控制台
                                console.log(dataToSend);
                            }
                        </script>
                        <?php
                        exit(); // 添加exit以避免继续执行下面的代码
                    } elseif ($_GET['verify'] === 'mobile') {
                        // 处理手机修改逻辑
                        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                            $newMobile = $_POST['new_mobile'] ?? '';
                            $verificationCode = $_POST['verification_code'] ?? '';
                            // 验证验证码
                            if (isset($_SESSION['verification_code']) && $_SESSION['verification_code'] == $verificationCode) {
                                // 更新手机
                                $updateMobileStmt = $pdo->prepare("UPDATE " . table('users') . " SET phone = :phone WHERE id = :id");
                                $updateMobileStmt->execute(['phone' => $newMobile, 'id' => $userId]);
                                $_SESSION['alert_message'] = '手机更新成功！';
                                header("Location: profile.php?message=update_success");
                                exit();
                            } else {
                                $_SESSION['alert_message'] = '验证码不正确！';
                                header("Location: profile.php?verify=mobile");
                                exit();
                            }
                        }
                        $secretKey = bin2hex(random_bytes(16));
                        $_SESSION['secret_key'] = $secretKey;
                        ?>
                        <h1 class="text-center">更新手机</h1>
                        <form method="post" action="profile.php?verify=mobile">
                            <div class="mb-3">
                                <label for="phone" class="form-label">当前手机:</label>
                                <input type="text" class="form-control"
                                    value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" readonly>
                            </div>
                            <div class="mb-3 row align-items-center">
                                <label for="new_mobile" class="form-label">新手机:</label>
                                <div class="col-12 col-sm-12">
                                    <input type="text" class="form-control" name="new_mobile" id="new_mobile" required>
                                </div>
                                <div style="margin-top: 1rem;" class="col-12 col-sm-12">
                                    <button type="button" class="btn btn-secondary col-12" onclick="sendVerificationCode()"
                                        style="white-space: nowrap;">发送验证码</button>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="verification_code" class="form-label">验证码:</label>
                                <input type="text" class="form-control" name="verification_code" id="verification_code"
                                    required>
                            </div>
                            <button type="submit" class="btn btn-primary col-12">确认更新</button>
                        </form>

                        <script>
                            function sendVerificationCode() {
                                // 使用 jQuery 获取新手机地址的值
                                var newMobile = $('#new_mobile').val();

                                if (!newMobile) {
                                    alert('请填写新手机地址。');
                                    return;
                                }

                                var secretKey = "<?php echo $secretKey; ?>";
                                var dataToSend = {
                                    mobile: newMobile,
                                    secret_key: secretKey
                                };

                                // 禁用按钮并改变样式
                                var button = document.querySelector("button[onclick='sendVerificationCode()']");
                                button.disabled = true;
                                button.classList.add('btn-secondary');
                                button.classList.remove('btn-primary');
                                button.innerText = '发送中...';

                                // AJAX 请求发送验证码
                                $.ajax({
                                    url: 'ajax.php', // 确保 AJAX 请求路径正确
                                    type: 'POST',
                                    contentType: 'application/json',
                                    data: JSON.stringify(dataToSend),
                                    dataType: 'json',
                                    success: function (response) {
                                        if (response.success) {
                                            alert(response.message); // 显示发送状态
                                        } else {
                                            alert('发送验证码失败: ' + response.message); // 显示错误信息
                                        }
                                        // 重新启用按钮
                                        button.disabled = false;

                                        button.classList.remove('btn-secondary');
                                        button.classList.add('btn-primary');
                                        button.innerText = '发送验证码';
                                    },
                                    error: function () {
                                        alert('请求发生错误。');
                                        // 重新启用按钮
                                        button.disabled = false;
                                        button.classList.remove('btn-secondary');
                                        button.classList.add('btn-primary');
                                        button.innerText = '发送验证码';
                                    }
                                });

                                // 在发送 AJAX 请求之前输出 data 到控制台
                                console.log(dataToSend);
                            }
                        </script>
                        <?php
                        exit(); // 添加exit以避免继续执行下面的代码
                    }
                }
                ?>

                <?php if (isset($_GET['realname'])): ?>

                    <?php if (!$isRealNameVerified): ?>
                        <h1 class="text-center">实名认证</h1>
                        <form method="post" action="profile.php?realname">
                            <div class="mb-3">
                                <label for="real_name" class="form-label">姓名:</label>
                                <input type="text" class="form-control" name="real_name" id="real_name"
                                    value="<?php echo htmlspecialchars($user['real_name'] ?? ''); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label for="id_card" class="form-label">身份证号码:</label>
                                <input type="text" class="form-control" name="id_card" id="id_card"
                                    value="<?php echo htmlspecialchars($user['id_card'] ?? ''); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label for="true_phone" class="form-label">实名手机号:</label>
                                <input type="text" class="form-control" name="true_phone" id="true_phone"
                                    value="<?php echo htmlspecialchars($user['true_phone'] ?? ''); ?>" required>
                            </div>
                            <button type="submit" class="btn btn-secondary">更新实名认证</button>
                        </form>
                    <?php else: ?>
                        <div class="alert alert-success" role="alert">
                            您已经完成实名认证。
                        </div>
                    <?php endif; ?>

                <?php elseif (isset($_GET['apikey'])): ?>
                    <?php if ($isApiAllowed): ?>
                        <h1 class="text-center">SPDNS ID和Key</h1>
                        <form method="post" action="profile.php?apikey" id="apikey-form">
                            <div class="mb-3">
                                <label for="spdnsid" class="form-label">SPDNS ID:</label>
                                <input type="text" class="form-control" name="spdnsid" id="spdnsid"
                                    value="<?php echo htmlspecialchars($user['spdnsid'] ?? ''); ?>" required>
                            </div>
                            <div class="mb-3">
                                <label for="spdnskey" class="form-label">SPDNS Key:</label>
                                <input type="text" class="form-control" name="spdnskey" id="spdnskey"
                                    value="<?php echo htmlspecialchars($user['spdnskey'] ?? ''); ?>" required>
                            </div>
                            <button type="button" class="btn btn-primary mt-2" onclick="generateSpdnsKey()">重新生成密钥</button>
                        </form>
                    <?php else: ?>
                        <div class="alert alert-danger" role="alert">
                            站点已开启权限认证，您没有API使用权限，请向站长申请。
                        </div>
                        <?php
                        $sql = "UPDATE " . table('users') . " SET spdnsid = ?, spdnskey = ? WHERE id = ?";
                        if ($stmt = $conn->prepare($sql)) {
                            $spdnsid = NULL;
                            $spdnskey = NULL;
                            $stmt->bind_param("ssi", $spdnsid, $spdnskey, $userId); // 绑定参数
                            $stmt->execute();
                            $stmt->close();
                        } else {
                            echo "数据库更新失败：" . $conn->error;
                        }
                        ?>

                    <?php endif; ?>
                <?php else: ?>
                    <h1 class="text-center">个人信息修改</h1>
                    <form method="post" action="profile.php">
                        <div class="mb-3">
                            <label for="username" class="form-label">用户名:</label>
                            <input type="text" class="form-control" name="username" id="username"
                                value="<?php echo htmlspecialchars($user['username'] ?? ''); ?>" disabled>
                        </div>
                        <div class="mb-3">
                            <label for="name" class="form-label">昵称:</label>
                            <input type="text" class="form-control" name="name" id="name"
                                value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="qq" class="form-label">QQ:</label>
                            <input type="text" class="form-control" name="qq" id="qq"
                                value="<?php echo htmlspecialchars($user['qq'] ?? ''); ?>" required>
                        </div>
                        <label for="email" class="form-label mb-3">邮箱:</label>
                        <div class="mb-3 col-12 d-flex align-items-center" style="white-space: nowrap;">
                            <input type="text" class="form-control me-2"
                                value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" readonly>
                            <button type="button" class="btn btn-secondary"
                                onclick="location.href='profile.php?verify=email'">更新邮箱</button>
                        </div>


                        <div class="mb-3">
                            <label for="phone" class="form-label">手机号:</label>
                            <div class="mb-3 col-12 d-flex align-items-center" style="white-space: nowrap;">
                            <input type="text" class="form-control me-2"
                                value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" readonly>
                                <button type="button" class="btn btn-secondary"
                                onclick="location.href='profile.php?verify=mobile'">更新手机</button>
                            </div>
                            </div>
                        <button type="submit" class="btn btn-primary col-12">更新资料</button>
                    </form>
                    <div class="mb-3 text-center" style="margin-top: 20px;">
                        <form action="./connect.php" method="get" role="form">
                            <?php if (empty($user['qq_uid'])): ?>
                                <button type="submit" name="type" value="qq" class="btn btn-success">QQ登录</button>
                            <?php else: ?>
                                <button type="submit" name="type" value="unbind_qq" class="btn btn-danger">解绑QQ</button>
                            <?php endif; ?>

                            <?php if (empty($user['wx_uid'])): ?>
                                <button type="submit" name="type" value="wx" class="btn btn-info">微信登录</button>
                            <?php else: ?>
                                <button type="submit" name="type" value="unbind_wx" class="btn btn-danger">解绑微信</button>
                            <?php endif; ?>

                            <?php if (empty($user['alipay_uid'])): ?>
                                <button type="submit" name="type" value="alipay" class="btn btn-warning">支付宝登录</button>
                            <?php else: ?>
                                <button type="submit" name="type" value="unbind_alipay" class="btn btn-danger">解绑支付宝</button>
                            <?php endif; ?>
                        </form>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <script src="../assets/js/popper.min.js"></script>
    <script src="../assets/js/bootstrap.min.js"></script>
    <script>
        // 生成随机密钥
        function generateKey(length) {
            const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
            let result = '';
            for (let i = 0; i < length; i++) {
                result += characters.charAt(Math.floor(Math.random() * characters.length));
            }
            return result;
        }

        function generateSpdnsKey() {
            if (confirm('确认要重新生成SPDNS ID和Key吗？')) {
                const spdnsidField = document.getElementById('spdnsid');
                const spdnskeyField = document.getElementById('spdnskey');
                spdnsidField.value = generateKey(12); // 生成12位SPDNS ID
                spdnskeyField.value = generateKey(12); // 生成12位SPDNS Key

                // 触发表单提交
                document.getElementById('apikey-form').submit();
            }
        }
    </script>
</body>

</html>