<?php
session_start();
require 'config.php';

// 检查登录状态
if (!isset($_SESSION['user_id'])) {
    header("Location: https://none.pw/auth");
    exit();
}

$user_id = $_SESSION['user_id'];
$username = $_SESSION['username'];

// 初始化聊天历史（Session + 数据库加载）
$_SESSION['chat_history'] = $_SESSION['chat_history'] ?? [];
if (empty($_SESSION['chat_history'])) {
    loadChatHistoryFromDatabase();
}

// 从数据库加载聊天记录
function loadChatHistoryFromDatabase() {
    global $conn, $user_id;
    $stmt = $conn->prepare("SELECT message, role FROM chat_history WHERE user_id = ? ORDER BY created_at ASC");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $_SESSION['chat_history'] = [];
    while ($row = $result->fetch_assoc()) {
        $_SESSION['chat_history'][] = [
            'role' => $row['role'],
            'content' => $row['message']
        ];
    }
    $stmt->close();
}

// 处理用户消息 & AI 回复
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['user_message'])) {
    $userMessage = trim($_POST['user_message']);
    if (!empty($userMessage)) {
        $selectedModel = $_POST['selected_model'] ?? 'deepseek-ai/DeepSeek-R1-Distill-Qwen-7B';
        $aiResponse = getAIResponse($userMessage, $selectedModel);

        if (isset($aiResponse['error'])) {
            echo json_encode(['status' => 'error', 'message' => $aiResponse['error']]);
        } else {
            if (deductCredits(1)) { // 扣积分逻辑
                saveChatMessage($user_id, $userMessage, 'user');
                saveChatMessage($user_id, $aiResponse['response'], 'bot');
                echo json_encode(['status' => 'success', 'response' => $aiResponse['response']]);
            } else {
                echo json_encode(['status' => 'error', 'message' => '积分不足，无法发送消息。']);
            }
        }
        exit;
    }
}

// 清空聊天记录（Session + 数据库）
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'clear_chat') {
    $_SESSION['chat_history'] = [];
    clearChatHistory($user_id);
    echo json_encode(['status' => 'success']);
    exit;
}

// 扣积分函数
function deductCredits($cost) {
    global $conn, $user_id;
    $stmt = $conn->prepare("SELECT points FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->bind_result($currentPoints);
    $stmt->fetch();
    $stmt->close();

    if ($currentPoints >= $cost) {
        $newPoints = $currentPoints - $cost;
        $stmt = $conn->prepare("UPDATE users SET points = ? WHERE id = ?");
        $stmt->bind_param("ii", $newPoints, $user_id);
        $stmt->execute();
        $stmt->close();
        return true;
    }
    return false;
}

// 获取 AI 回复（CURL 请求）
function getAIResponse($message, $model) {
    $API_KEY = 'sk-oqimqihyuumdzecwypfvekslpigmtlyjjzytvccwimhutlqc';
    $API_URL = 'https://api.siliconflow.cn/v1/chat/completions';

    $headers = [
        'Authorization: Bearer ' . $API_KEY,
        'Content-Type: application/json'
    ];

    $data = [
        'model' => $model,
        'messages' => [['role' => 'user', 'content' => $message]],
        'max_tokens' => 4096
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $API_URL);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        $error_msg = curl_error($ch);
        curl_close($ch);
        return ["error" => "网络请求错误: " . $error_msg];
    }

    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($httpCode != 200) {
        return ["error" => "AI 服务返回了状态码: " . $httpCode];
    }

    $result = json_decode($response, true);
    if (isset($result['choices']) && count($result['choices']) > 0) {
        return ["response" => $result['choices'][0]['message']['content']];
    } else {
        return ["error" => "AI 服务返回了无效的响应: " . $response];
    }
}

// 保存聊天记录到数据库
function saveChatMessage($userId, $message, $role) {
    global $conn;
    $stmt = $conn->prepare("INSERT INTO chat_history (user_id, message, role, created_at) VALUES (?, ?, ?, NOW())");
    $stmt->bind_param("iss", $userId, $message, $role);
    $stmt->execute();
    $stmt->close();
}

// 清空数据库聊天记录
function clearChatHistory($userId) {
    global $conn;
    $stmt = $conn->prepare("DELETE FROM chat_history WHERE user_id = ?");
    $stmt->bind_param("i", $userId);
    $stmt->execute();
    $stmt->close();
}

// 查询用户等级 & 积分
$stmt = $conn->prepare("SELECT level, points FROM users WHERE id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($level, $points);
$stmt->fetch();
$stmt->close();
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <!-- 引入 Tailwind CSS（CDN 方式，生产建议用本地构建） -->
  <script src="https://cdn.tailwindcss.com"></script>
  <title>AI 智能聊天</title>
  <style>
    /* 自定义滚动条（仅 WebKit 内核浏览器） */
    ::-webkit-scrollbar { width: 8px; }
    ::-webkit-scrollbar-track { background: #f1f1f1; }
    ::-webkit-scrollbar-thumb { background: #c1c1c1; border-radius: 4px; }
    ::-webkit-scrollbar-thumb:hover { background: #a1a1a1; }
  </style>
</head>
<body class="bg-gray-100 font-sans leading-normal tracking-normal">
  <!-- 主容器：居中、限制宽度、留白 -->
  <div class="mx-auto max-w-3xl px-4 sm:px-6 lg:px-8 min-h-screen flex flex-col">
    
    <!-- 顶部区域：简单标题（可扩展为导航） -->
    <header class="py-6">
      <h1 class="text-2xl font-bold text-gray-800">
        AI 智能聊天
      </h1>
    </header>

    <!-- 聊天主卡片：阴影、圆角、内边距 -->
    <div class="flex-1 bg-white rounded-lg shadow p-6 space-y-6">
      
      <!-- 模型选择器：简洁下拉框 -->
      <div class="flex items-center space-x-4">
        <label for="modelSelect" class="text-gray-700">选择模型：</label>
        <select id="modelSelect" class="border border-gray-300 rounded px-2 py-1 focus:outline-none focus:ring-2 focus:ring-blue-500">
          <option value="deepseek-ai/DeepSeek-R1-Distill-Qwen-7B">DeepSeek-R1-7B</option>
          <option value="deepseek-ai/DeepSeek-R1-Distill-Qwen-14B">DeepSeek-R1-14B</option>
        </select>
      </div>

      <!-- 聊天历史容器：高 400px、自动滚动、留白 -->
      <div id="chatHistory" class="h-64 overflow-y-auto p-4 bg-gray-50 rounded space-y-4">
        <?php foreach ($_SESSION['chat_history'] as $message): ?>
          <div class="p-3 rounded <?= $message['role'] === 'user' ? 'bg-green-100' : 'bg-blue-100' ?>">
            <p class="text-sm text-gray-800">
              <?= htmlspecialchars($message['content']) ?>
            </p>
          </div>
        <?php endforeach; ?>
      </div>

      <!-- 输入区域：自适应、按钮分组 -->
      <div class="flex flex-col sm:flex-row space-y-4 sm:space-y-0 sm:space-x-4">
        <textarea 
          id="userMessage" 
          placeholder="发消息、输入 @选择技能 / 选择文件" 
          class="flex-1 border border-gray-300 rounded p-2 focus:outline-none focus:ring-2 focus:ring-blue-500"
          rows="3"
          autocomplete="off"
        ></textarea>
        
        <div class="flex space-x-2">
          <button 
            onclick="sendMessage()" 
            class="px-4 py-2 bg-green-500 text-white rounded hover:bg-green-600 focus:outline-none focus:ring-2 focus:ring-green-500"
          >
            发送
          </button>
          <button 
            onclick="clearChatHistory()" 
            class="px-4 py-2 bg-red-500 text-white rounded hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500"
          >
            清空记录
          </button>
        </div>
      </div>

      <!-- 底部信息：积分、运营说明 -->
      <div class="text-sm text-gray-600 flex justify-between">
        <p>积分: <?= $points ?> | 内测版本，消耗 1 积分</p>
        <a href="../console" class="text-blue-500 hover:underline">返回用户后台</a>
      </div>
    </div>

    <!-- 底部功能栏（参考豆包样式） -->
    <footer class="py-4 flex justify-between items-center border-t">
      <div class="flex space-x-2">
        <button class="px-3 py-2 bg-gray-50 text-gray-700 rounded hover:bg-gray-100">深度思考</button>
        <button class="px-3 py-2 bg-gray-50 text-gray-700 rounded hover:bg-gray-100">技能</button>
      </div>
      <div class="flex space-x-2">
        <button class="px-3 py-2 bg-gray-50 text-gray-700 rounded hover:bg-gray-100">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
          </svg>
        </button>
        <button class="px-3 py-2 bg-gray-50 text-gray-700 rounded hover:bg-gray-100">
          <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 16.5v-2.5m0 0v-2.5c0-1.103-.897-2-2-2h-4c-1.103 0-2 .897-2 2v6.5c0 1.103.897 2 2 2h4c1.103 0 2-.897 2-2zm0 0h8" />
          </svg>
        </button>
      </div>
    </footer>
  </div>

  <!-- JavaScript 交互逻辑 -->
  <script>
    // 发送消息
    function sendMessage() {
      const userMessage = document.getElementById('userMessage').value.trim();
      if (!userMessage) return;

      const selectedModel = document.getElementById('modelSelect').value;
      addMessage(userMessage, 'user');
      addMessage('回复中...', 'bot');
      document.getElementById('userMessage').value = '';

      fetch(window.location.href, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `user_message=${encodeURIComponent(userMessage)}&selected_model=${encodeURIComponent(selectedModel)}`
      })
      .then(res => res.json())
      .then(data => {
        const chatHistory = document.getElementById('chatHistory');
        const lastBotMsg = chatHistory.lastElementChild;
        
        // 替换“回复中...”占位
        if (lastBotMsg?.textContent === '回复中...' && lastBotMsg.classList.contains('bg-blue-100')) {
          chatHistory.removeChild(lastBotMsg);
        }

        if (data.status === 'success') {
          addMessage(data.response, 'bot');
        } else {
          addMessage(data.message || '请求失败，请重试', 'bot');
        }
      })
      .catch(err => {
        console.error('请求异常:', err);
        const chatHistory = document.getElementById('chatHistory');
        const lastBotMsg = chatHistory.lastElementChild;
        
        if (lastBotMsg?.textContent === '回复中...' && lastBotMsg.classList.contains('bg-blue-100')) {
          chatHistory.removeChild(lastBotMsg);
        }
        addMessage('服务器繁忙，请稍后再试', 'bot');
      });
    }

    // 添加聊天消息到页面
    function addMessage(content, role) {
      const chatHistory = document.getElementById('chatHistory');
      const msgDiv = document.createElement('div');
      msgDiv.className = `p-3 rounded ${role === 'user' ? 'bg-green-100' : 'bg-blue-100'}`;
      msgDiv.textContent = content;
      chatHistory.appendChild(msgDiv);
      chatHistory.scrollTop = chatHistory.scrollHeight; // 滚动到底部
    }

    // 清空聊天记录
    function clearChatHistory() {
      document.getElementById('chatHistory').innerHTML = '';
      fetch(window.location.href, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: 'action=clear_chat'
      })
      .then(res => res.json())
      .then(data => {
        if (data.status === 'success') {
          localStorage.removeItem('chatHistory'); // 可选：清理本地缓存
        }
      });
    }

    // 回车发送消息
    document.getElementById('userMessage').addEventListener('keypress', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) { // 按住 Shift 可换行
        e.preventDefault();
        sendMessage();
      }
    });
  </script>
</body>
</html>