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

$patient_id = $_SESSION['patient_id'];

// Get staff conversations
$staff_chats = $conn->query("
    SELECT DISTINCT s.staff_id, s.first_name, s.last_name,
        (SELECT message FROM staff_patient_chat WHERE patient_id = '$patient_id' AND staff_id = s.staff_id ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM staff_patient_chat WHERE patient_id = '$patient_id' AND staff_id = s.staff_id ORDER BY created_at DESC LIMIT 1) as last_date,
        (SELECT COUNT(*) FROM staff_patient_chat WHERE patient_id = '$patient_id' AND staff_id = s.staff_id AND sender = 'staff' AND is_read = 0) as unread
    FROM staff_patient_chat spc
    JOIN staff s ON spc.staff_id = s.staff_id
    WHERE spc.patient_id = '$patient_id'
    GROUP BY s.staff_id
    ORDER BY last_date DESC
");

$selected_staff = null;
$messages = null;
if (isset($_GET['staff_id'])) {
    $staff_id = (int)$_GET['staff_id'];
    $selected_staff = $conn->query("SELECT staff_id, first_name, last_name, department FROM staff WHERE staff_id = $staff_id")->fetch_assoc();
    $messages = $conn->query("SELECT * FROM staff_patient_chat WHERE patient_id = '$patient_id' AND staff_id = $staff_id ORDER BY created_at ASC");
    $conn->query("UPDATE staff_patient_chat SET is_read = 1 WHERE patient_id = '$patient_id' AND staff_id = $staff_id AND sender = 'staff'");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $staff_id = (int)$_POST['staff_id'];
    $message = $conn->real_escape_string($_POST['message']);
    
    $stmt = $conn->prepare("INSERT INTO staff_patient_chat (staff_id, patient_id, message, sender) VALUES (?, ?, ?, 'patient')");
    $stmt->bind_param("iss", $staff_id, $patient_id, $message);
    $stmt->execute();
    
    header("Location: staff_chat.php?staff_id=$staff_id");
    exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Chat with Hospital Staff</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;}.navbar{background:#064e3b;}.card{border-radius:20px;background:rgba(255,255,255,0.95);}.messages-container{height:400px;overflow-y:auto;padding:15px;background:#f9f9f9;border-radius:15px;}.message-patient{text-align:right;margin-bottom:15px;}.message-patient .bubble{background:#0f6b4c;color:white;display:inline-block;padding:10px 15px;border-radius:20px 20px 5px 20px;max-width:70%;}.message-staff{text-align:left;margin-bottom:15px;}.message-staff .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;}.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;}</style></head>
<body><nav class="navbar navbar-dark"><div class="container"><span class="navbar-brand"><i class="fas fa-headset"></i> Hospital Staff Support</span><a href="dashboard.php" class="btn btn-light btn-sm">Back</a></div></nav>
<div class="container mt-4"><div class="row">
    <div class="col-md-4"><div class="card"><div class="card-header bg-success text-white">Support Staff</div><div class="card-body p-0">
        <?php if($staff_chats && $staff_chats->num_rows > 0): ?>
            <?php while($s = $staff_chats->fetch_assoc()): ?>
                <a href="?staff_id=<?= $s['staff_id'] ?>" class="chat-item d-block text-decoration-none <?= (isset($_GET['staff_id']) && $_GET['staff_id'] == $s['staff_id']) ? 'active' : '' ?>">
                    <div class="d-flex justify-content-between"><strong><?= htmlspecialchars($s['first_name'] . ' ' . $s['last_name']) ?></strong><?php if($s['unread'] > 0): ?><span class="unread-badge"><?= $s['unread'] ?></span><?php endif; ?></div>
                    <small class="text-muted"><?= htmlspecialchars(substr($s['last_message'],0,40)) ?>...</small>
                </a>
            <?php endwhile; ?>
        <?php else: ?><div class="p-3 text-muted">No staff conversations yet.</div><?php endif; ?>
    </div></div></div>
    <div class="col-md-8"><div class="card"><div class="card-header bg-info text-white"><?= $selected_staff ? 'Chat with ' . htmlspecialchars($selected_staff['first_name'] . ' ' . $selected_staff['last_name']) . ' (' . ucfirst($selected_staff['department']) . ')' : 'Select a staff member' ?></div>
    <div class="card-body p-0" style="height: 500px; display: flex; flex-direction: column;">
        <?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'] == 'patient' ? 'patient' : 'staff' ?>">
                            <div class="bubble"><?= nl2br(htmlspecialchars($m['message'])) ?><div class="small mt-1"><?= date('h:i A', strtotime($m['created_at'])) ?></div></div>
                        </div>
                    <?php endwhile; ?>
                <?php else: ?><div class="text-center text-muted py-5">No messages yet.</div><?php endif; ?>
            </div>
            <form method="POST" class="p-3 border-top"><input type="hidden" name="staff_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 staff member to start chatting.</p></div><?php endif; ?>
    </div></div></div>
</div></div>
<script>var c=document.getElementById('messagesContainer');if(c)c.scrollTop=c.scrollHeight;</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>