<?php
ob_start();
session_start();
error_reporting(0);

// 数据库全部 = 6
$db_host = 'localhost';
$db_name = '11';
$db_user = '11';
$db_pass = '11';
$db_port = 3306;

$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name, $db_port);
mysqli_set_charset($conn, 'utf8mb4');

// 自动建表
mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `users` (
  `uid` varchar(64) PRIMARY KEY,
  `name` varchar(32) NOT NULL,
  created_at datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

mysqli_query($conn, "
CREATE TABLE IF NOT EXISTS `messages` (
  `id` int AUTO_INCREMENT PRIMARY KEY,
  `uid` varchar(64) NOT NULL,
  `from_role` enum('user','admin') NOT NULL,
  `content` text NOT NULL,
  send_at datetime DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// 用户初始化：用户1、用户2、用户3...
if (empty($_SESSION['uid'])) {
    $res = mysqli_query($conn, "SELECT MAX(CAST(SUBSTRING(name,3) AS UNSIGNED)) as n FROM users WHERE name LIKE '用户%'");
    $row = mysqli_fetch_assoc($res);
    $n = $row['n'] ?? 0;

    $uid = 'u' . uniqid();
    $name = '用户' . ($n + 1);

    $_SESSION['uid'] = $uid;
    $_SESSION['name'] = $name;
    $_SESSION['last_id'] = 0;

    mysqli_query($conn, "INSERT IGNORE INTO users (uid,name) VALUES ('$uid','$name')");
    mysqli_query($conn, "INSERT INTO messages (uid,from_role,content) VALUES ('$uid','admin','你好，有什么可以帮你的？')");
}

$uid       = $_SESSION['uid'];
$name      = $_SESSION['name'];
$last_id   = $_SESSION['last_id'] ?? 0;
$is_admin  = !empty($_SESSION['is_admin']);

// 管理员登录
if (isset($_POST['admin_login'])) {
    if ($_POST['pwd'] === '三玖nb') {
        $_SESSION['is_admin'] = 1;
        header("Location: index.php");
        exit;
    }
}

// 退出
if (isset($_GET['logout'])) {
    session_destroy();
    header("Location: index.php");
    exit;
}

// 发送消息接口
if (isset($_POST['content'])) {
    $content = trim($_POST['content']);
    if ($content) {
        if ($is_admin && !empty($_POST['to_uid'])) {
            $to_uid = $_POST['to_uid'];
            mysqli_query($conn, "INSERT INTO messages (uid,from_role,content) VALUES ('$to_uid','admin','$content')");
        } else {
            mysqli_query($conn, "INSERT INTO messages (uid,from_role,content) VALUES ('$uid','user','$content')");
        }
    }
    exit;
}

// 拉取消息接口
if (isset($_GET['get_msg'])) {
    header('Content-Type: application/json');
    $chat_uid = $_GET['chat_uid'] ?? $uid;
    $last = (int)$_GET['last_id'];

    $res = mysqli_query($conn, "SELECT * FROM messages WHERE uid='$chat_uid' AND id>$last ORDER BY id ASC");
    $msgs = [];
    while ($m = mysqli_fetch_assoc($res)) $msgs[] = $m;

    if ($msgs) $_SESSION['last_id'] = $msgs[count($msgs)-1]['id'];
    echo json_encode(['msgs' => $msgs]);
    exit;
}

// 历史消息
function get_history($conn, $uid) {
    $res = mysqli_query($conn, "SELECT * FROM messages WHERE uid='$uid' ORDER BY id ASC");
    $arr = [];
    while ($m = mysqli_fetch_assoc($res)) $arr[] = $m;
    return $arr;
}

$my_msgs    = get_history($conn, $uid);
$chat_uid   = $_GET['chat'] ?? '';
$chat_msgs  = $chat_uid ? get_history($conn, $chat_uid) : [];

// 用户列表
$users = [];
$res = mysqli_query($conn, "SELECT * FROM users ORDER BY created_at DESC");
while ($u = mysqli_fetch_assoc($res)) $users[] = $u;
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>客服系统</title>
<style>
*{box-sizing:border-box;margin:0;padding:0;font-family:system-ui}
html,body{height:100%;width:100%;background:#f5f7fa}
#adminBtn{position:fixed;top:6px;right:8px;font-size:12px;border:none;background:none;color:#888;cursor:pointer}
.loginModal{position:fixed;inset:0;background:rgba(0,0,0,.5);display:none;align-items:center;justify-content:center}
.loginBox{background:#fff;padding:24px;border-radius:12px;width:320px}
.loginBox input{width:100%;padding:10px;margin:10px 0;border:1px solid #ddd;border-radius:8px}
.loginBox button{width:100%;padding:10px;background:#007bff;color:#fff;border:none;border-radius:8px}
.main{display:flex;height:100vh}
.userList{width:240px;background:#fff;border-right:1px solid #eee;padding:12px;overflow-y:auto}
.userItem{padding:10px;background:#f8f9fa;border-radius:8px;margin-bottom:6px}
.userItem.active{background:#e6f7ff;color:#007bff}
.chat{flex:1;display:flex;flex-direction:column;height:100vh}
.head{padding:14px;background:#fff;border-bottom:1px solid #eee;font-weight:bold}
.msgBox{flex:1;padding:16px;overflow-y:auto;display:flex;flex-direction:column;gap:8px}
.msg{max-width:75%;padding:8px 12px;border-radius:12px}
.msg.user{align-self:flex-end;background:#007bff;color:#fff}
.msg.admin{align-self:flex-start;background:#e9ecef}
.inputBar{display:flex;padding:10px;background:#fff;border-top:1px solid #eee}
.inputBar input{flex:1;padding:10px 16px;border:1px solid #ddd;border-radius:24px;outline:none}
.inputBar button{margin-left:8px;padding:0 20px;background:#007bff;color:#fff;border:none;border-radius:24px}
</style>
</head>
<body>

<button id="adminBtn">管理员登录</button>
<div class="loginModal" id="loginModal">
    <div class="loginBox">
        <h4>管理员登录</h4>
        <form method="post">
            <input type="password" name="pwd" placeholder="请输入密码" required>
            <button type="submit" name="admin_login">登录</button>
        </form>
    </div>
</div>

<?php if(!$is_admin): ?>
<!-- 用户界面 -->
<div class="chat">
    <div class="head">客服对话 · <?=$name?></div>
    <div class="msgBox" id="msgBox">
        <?php foreach($my_msgs as $m): ?>
            <div class="msg <?=$m['from_role']?>"><?=htmlspecialchars($m['content'])?></div>
        <?php endforeach; ?>
    </div>
    <form class="inputBar" id="sendForm">
        <input type="text" name="content" id="inputText" placeholder="输入消息..." required>
        <button type="submit">发送</button>
    </form>
</div>

<?php else: ?>
<!-- 管理员界面 -->
<div class="main">
    <div class="userList">
        <h4>用户列表</h4>
        <?php foreach($users as $u): ?>
            <a href="?chat=<?=$u['uid']?>" style="text-decoration:none;color:inherit">
                <div class="userItem <?=$u['uid']==$chat_uid?'active':''?>">
                    <?=$u['name']?>
                </div>
            </a>
        <?php endforeach; ?>
        <br><a href="?logout=1" style="color:red">退出登录</a>
    </div>

    <div class="chat">
        <div class="head">
            <?php if($chat_uid): ?>
                对话：<?=$users[array_search($chat_uid,array_column($users,'uid'))]['name']?>
            <?php else: ?>请选择用户<?php endif; ?>
        </div>
        <div class="msgBox" id="msgBox">
            <?php if($chat_uid): foreach($chat_msgs as $m): ?>
                <div class="msg <?=$m['from_role']?>"><?=htmlspecialchars($m['content'])?></div>
            <?php endforeach; endif; ?>
        </div>

        <?php if($chat_uid): ?>
        <form class="inputBar" id="sendForm">
            <input type="hidden" name="to_uid" value="<?=$chat_uid?>">
            <input type="text" name="content" id="inputText" placeholder="输入消息..." required>
            <button type="submit">发送</button>
        </form>
        <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<script>
// 登录弹窗
document.getElementById('adminBtn').onclick = function(){
    document.getElementById('loginModal').style.display = 'flex';
}
document.getElementById('loginModal').onclick = function(e){
    if(e.target === this) this.style.display = 'none';
}

// 全局变量
const uid = '<?=$uid?>';
const isAdmin = <?=$is_admin ? 'true' : 'false'?>;
const chatUid = '<?=$chat_uid?>';
let lastId = <?=$last_id?>;

// 发送表单（已修复 this 指向问题）
const form = document.getElementById('sendForm');
const input = document.getElementById('inputText');
const msgBox = document.getElementById('msgBox');

if(form){
    form.onsubmit = function(e){
        e.preventDefault();
        const content = input.value.trim();
        if(!content) return;

        let fd = new FormData();
        fd.append('content', content);
        if(isAdmin && chatUid) fd.append('to_uid', chatUid);

        fetch('index.php', {
            method: 'POST',
            body: fd
        }).then(() => {
            input.value = '';  // 清空输入框
            getMsg();          // 立刻拉取消息
        });
    };
}

// 拉取消息
function getMsg(){
    let url = `index.php?get_msg=1&uid=${uid}&last_id=${lastId}`;
    if(isAdmin && chatUid) url += `&chat_uid=${chatUid}`;

    fetch(url)
    .then(res => res.json())
    .then(data => {
        data.msgs.forEach(m => {
            let div = document.createElement('div');
            div.className = 'msg ' + m.from_role;
            div.innerText = m.content;
            msgBox.appendChild(div);
        });
        if(data.msgs.length) lastId = data.msgs.at(-1).id;
        msgBox.scrollTop = msgBox.scrollHeight;
    });
}

// 每秒拉取一次
setInterval(getMsg, 1000);
window.onload = getMsg;
</script>
</body>
</html>
