<?php
session_start();
if (!isset($_SESSION['staff_id'])) { header("Location: login.php"); exit(); }
include '../include/config.php';

$staff_id = $_SESSION['staff_id'];
$staff_name = $_SESSION['staff_name'];
$staff_department = $_SESSION['staff_department'];

// Get all staff except self
$all_staff = $conn->query("SELECT staff_id, first_name, last_name, department, position FROM staff WHERE staff_id != $staff_id AND status = 'active' ORDER BY first_name");

// Get recent conversations
$conversations = $conn->query("
    SELECT DISTINCT 
        CASE 
            WHEN sender_id = $staff_id THEN receiver_id 
            ELSE sender_id 
        END as other_staff_id,
        (SELECT CONCAT(first_name, ' ', last_name) FROM staff WHERE staff_id = other_staff_id) as other_name,
        (SELECT department FROM staff WHERE staff_id = other_staff_id) as other_department,
        (SELECT message FROM staff_staff_chat 
         WHERE (sender_id = $staff_id AND receiver_id = other_staff_id) 
            OR (sender_id = other_staff_id AND receiver_id = $staff_id) 
         ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM staff_staff_chat 
         WHERE (sender_id = $staff_id AND receiver_id = other_staff_id) 
            OR (sender_id = other_staff_id AND receiver_id = $staff_id) 
         ORDER BY created_at DESC LIMIT 1) as last_date,
        (SELECT COUNT(*) FROM staff_staff_chat 
         WHERE receiver_id = $staff_id AND sender_id = other_staff_id AND is_read = 0) as unread
    FROM staff_staff_chat
    WHERE sender_id = $staff_id OR receiver_id = $staff_id
    GROUP BY other_staff_id
    ORDER BY last_date DESC
");

// Get messages for selected staff
$selected_staff = null;
$messages = null;
if (isset($_GET['chat_with'])) {
    $chat_with = (int)$_GET['chat_with'];
    $selected_staff = $conn->query("SELECT staff_id, first_name, last_name, department, position FROM staff WHERE staff_id = $chat_with")->fetch_assoc();
    $messages = $conn->query("
        SELECT * FROM staff_staff_chat 
        WHERE (sender_id = $staff_id AND receiver_id = $chat_with) 
           OR (sender_id = $chat_with AND receiver_id = $staff_id) 
        ORDER BY created_at ASC
    ");
    // Mark as read
    $conn->query("UPDATE staff_staff_chat SET is_read = 1 WHERE receiver_id = $staff_id AND sender_id = $chat_with");
}

// Send message
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $receiver_id = (int)$_POST['receiver_id'];
    $message = $conn->real_escape_string($_POST['message']);
    
    $stmt = $conn->prepare("INSERT INTO staff_staff_chat (sender_id, receiver_id, message) VALUES (?, ?, ?)");
    $stmt->bind_param("iis", $staff_id, $receiver_id, $message);
    $stmt->execute();
    
    header("Location: staff_chat.php?chat_with=$receiver_id");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Staff-to-Staff Chat - UHD</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.6.0/css/all.min.css">
    <style>
        body { background: #0a3d2f; font-family: 'Segoe UI', sans-serif; }
        .navbar { background: #064e3b !important; }
        .card { border-radius: 20px; background: rgba(255,255,255,0.95); }
        .messages-container { height: 450px; overflow-y: auto; padding: 15px; background: #f9f9f9; border-radius: 15px; }
        .message-me { text-align: right; margin-bottom: 15px; }
        .message-me .bubble { background: #0f6b4c; color: white; display: inline-block; padding: 10px 15px; border-radius: 20px 20px 5px 20px; max-width: 70%; }
        .message-other { text-align: left; margin-bottom: 15px; }
        .message-other .bubble { background: #e9ecef; color: #333; display: inline-block; padding: 10px 15px; border-radius: 20px 20px 20px 5px; max-width: 70%; }
        .chat-item { cursor: pointer; padding: 12px; border-bottom: 1px solid #eee; text-decoration: none; display: block; }
        .chat-item:hover { background: #f0fdf4; }
        .chat-item.active { background: #f0fdf4; border-left: 4px solid #0f6b4c; }
        .unread-badge { background: #dc3545; color: white; border-radius: 50%; padding: 2px 6px; font-size: 10px; margin-left: 5px; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark">
    <div class="container">
        <span class="navbar-brand"><i class="fas fa-comments"></i> Staff Collaboration Chat</span>
        <div>
            <span class="text-white me-2"><i class="fas fa-user-tie"></i> <?= htmlspecialchars($staff_name) ?> (<?= ucfirst($staff_department) ?>)</span>
            <a href="dashboard.php" class="btn btn-light btn-sm">Back</a>
        </div>
    </div>
</nav>

<div class="container mt-4">
    <div class="row">
        <!-- Staff List -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h6 class="mb-0"><i class="fas fa-users"></i> Colleagues</h6>
                </div>
                <div class="card-body p-0" style="max-height: 550px; overflow-y: auto;">
                    <?php if($all_staff && $all_staff->num_rows > 0): ?>
                        <?php while($s = $all_staff->fetch_assoc()): 
                            $unread = $conn->query("SELECT COUNT(*) as cnt FROM staff_staff_chat WHERE receiver_id = $staff_id AND sender_id = {$s['staff_id']} AND is_read = 0")->fetch_assoc()['cnt'] ?? 0;
                        ?>
                            <a href="?chat_with=<?= $s['staff_id'] ?>" class="chat-item <?= (isset($_GET['chat_with']) && $_GET['chat_with'] == $s['staff_id']) ? 'active' : '' ?>">
                                <div class="d-flex justify-content-between">
                                    <div>
                                        <i class="fas fa-user-circle"></i>
                                        <strong><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?></strong>
                                        <br><small class="text-muted"><?= ucfirst($s['department']) ?> - <?= ucfirst($s['position']) ?></small>
                                    </div>
                                    <?php if($unread > 0): ?>
                                        <span class="unread-badge"><?= $unread ?></span>
                                    <?php endif; ?>
                                </div>
                            </a>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="p-3 text-muted">No other staff members found.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Chat Area -->
        <div class="col-md-8">
            <div class="card h-100">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0">
                        <?php if($selected_staff): ?>
                            <i class="fas fa-user-circle"></i> <?= htmlspecialchars($selected_staff['first_name'] . ' ' . $selected_staff['last_name']) ?> (<?= ucfirst($selected_staff['department']) ?>)
                        <?php else: ?>
                            <i class="fas fa-comments"></i> Select a colleague to chat
                        <?php endif; ?>
                    </h6>
                </div>
                <div class="card-body p-0 d-flex flex-column" style="height: 550px;">
                    <?php if($selected_staff): ?>
                        <div class="messages-container" id="messagesContainer">
                            <?php if($messages && $messages->num_rows > 0): ?>
                                <?php while($m = $messages->fetch_assoc()): ?>
                                    <div class="message-<?= ($m['sender_id'] == $staff_id) ? 'me' : 'other' ?>">
                                        <div class="bubble">
                                            <?= nl2br(htmlspecialchars($m['message'])) ?>
                                            <div class="small mt-1 opacity-50"><?= date('h:i A', strtotime($m['created_at'])) ?></div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-comment-dots fa-3x mb-3"></i>
                                    <p>No messages yet. Start a conversation with <?= htmlspecialchars($selected_staff['first_name']) ?></p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <form method="POST" class="p-3 border-top">
                            <input type="hidden" name="receiver_id" value="<?= $selected_staff['staff_id'] ?>">
                            <div class="input-group">
                                <textarea name="message" class="form-control" rows="2" placeholder="Type your message..." required></textarea>
                                <button type="submit" name="send_message" class="btn btn-primary">Send</button>
                            </div>
                        </form>
                    <?php else: ?>
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-inbox fa-4x mb-3"></i>
                            <p>Select a colleague from the left to start chatting.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var container = document.getElementById('messagesContainer');
    if (container) container.scrollTop = container.scrollHeight;
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>