<?php
include 'header.php';
if (!isset($_SESSION['user_id'])) {
    echo "<script>location.href='login.php';</script>";
    exit;
}

$user_id = $_SESSION['user_id'];
$pdo = db();

// Fetch user info for UID
$stmt = $pdo->prepare("SELECT uid, username FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// Get user IP
$user_ip = $_SERVER['REMOTE_ADDR'];
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $user_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}

// Handle message sending
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['message'])) {
    $msg = trim($_POST['message']);
    if ($msg !== '') {
        $stmt = $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
        $stmt->execute([$user_id, $msg]);
    }
    header("Location: chat.php");
    exit;
}

// Fetch messages
$stmt = $pdo->prepare("SELECT * FROM messages WHERE user_id = ? ORDER BY created_at ASC");
$stmt->execute([$user_id]);
$messages = $stmt->fetchAll();

// Mark admin messages as read
$stmt = $pdo->prepare("UPDATE messages SET is_read = 1 WHERE user_id = ? AND sender = 'admin'");
$stmt->execute([$user_id]);
?>

<div class="container" style="max-width: 800px; margin: 40px auto; padding: 0 20px;">
    <div class="card" style="background: var(--card-bg); border: 1px solid var(--border-color); border-radius: 16px; display: flex; flex-direction: column; height: 600px;">
        <div class="card-header" style="padding: 20px; border-bottom: 1px solid var(--border-color); display: flex; align-items: center; gap: 15px;">
            <div style="width: 40px; height: 40px; background: var(--primary-color); border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                <i class="fas fa-headset"></i>
            </div>
            <div>
                <h3 style="margin: 0; font-size: 18px;"><?php echo __('customer_service', '在线客服'); ?></h3>
                <span style="font-size: 12px; color: var(--success-color);"><i class="fas fa-circle" style="font-size: 8px;"></i> 在线</span>
            </div>
        </div>
        
        <div id="chat-box" style="flex: 1; overflow-y: auto; padding: 20px; display: flex; flex-direction: column; gap: 15px; scroll-behavior: smooth;">
            <!-- User Identification Info -->
            <div style="text-align: center; margin-bottom: 20px;">
                <div style="display: inline-block; padding: 8px 16px; background: rgba(255, 255, 255, 0.05); border-radius: 20px; font-size: 12px; color: var(--text-muted);">
                    <i class="fas fa-info-circle" style="margin-right: 5px;"></i>
                    当前用户: <span style="color: white;"><?php echo htmlspecialchars($user['username']); ?></span> (UID: <?php echo $user['uid']; ?>) 
                    | 登录IP: <span style="color: white;"><?php echo $user_ip; ?></span>
                </div>
            </div>

            <?php if (empty($messages)): ?>
                <div style="text-align: center; color: var(--text-muted); margin-top: 50px;">
                    <i class="fas fa-comments" style="font-size: 48px; opacity: 0.2; margin-bottom: 15px;"></i>
                    <p><?php echo __('chat_welcome', '您好！请问有什么可以帮您？'); ?></p>
                </div>
            <?php endif; ?>
            
            <?php foreach ($messages as $m): ?>
                <div style="display: flex; flex-direction: column; align-items: <?php echo $m['sender'] === 'user' ? 'flex-end' : 'flex-start'; ?>;">
                    <div style="max-width: 70%; padding: 12px 16px; border-radius: 12px; font-size: 14px; line-height: 1.5; 
                        <?php echo $m['sender'] === 'user' ? 'background: var(--primary-color); color: white; border-bottom-right-radius: 2px;' : 'background: #2b3139; color: white; border-bottom-left-radius: 2px;'; ?>">
                        <?php echo nl2br(htmlspecialchars($m['message'])); ?>
                    </div>
                    <span style="font-size: 10px; color: var(--text-muted); margin-top: 4px;"><?php echo date('H:i', strtotime($m['created_at'])); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="chat-input" style="padding: 20px; border-top: 1px solid var(--border-color);">
            <form method="POST" style="display: flex; gap: 10px;">
                <input type="text" name="message" autocomplete="off" placeholder="<?php echo __('type_message', '请输入消息...'); ?>" 
                    style="flex: 1; background: #2b3139; border: 1px solid var(--border-color); border-radius: 8px; padding: 12px 15px; color: white; outline: none;">
                <button type="submit" class="btn-primary" style="padding: 0 25px; border-radius: 8px;">
                    <i class="fas fa-paper-plane"></i>
                </button>
            </form>
        </div>
    </div>
</div>

<script>
    const chatBox = document.getElementById('chat-box');
    chatBox.scrollTop = chatBox.scrollHeight;
    
    // Auto refresh chat
    setInterval(() => {
        fetch('api/get_messages.php')
            .then(r => r.json())
            .then(data => {
                if (data.count > <?php echo count($messages); ?>) {
                    location.reload();
                }
            });
    }, 3000);
</script>

<?php include 'footer.php'; ?>