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

$doctor_id = $_SESSION['doctor_id'];
$doctor_name = $_SESSION['doctor_name'];

// Ensure table exists
$conn->query("CREATE TABLE IF NOT EXISTS staff_doctor_chat (
    id INT AUTO_INCREMENT PRIMARY KEY,
    staff_id INT NOT NULL,
    doctor_id INT NOT NULL,
    message TEXT NOT NULL,
    sender ENUM('staff','doctor') DEFAULT 'staff',
    is_read TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

// Get all staff with profile photos
$all_staff = $conn->query("
    SELECT staff_id, first_name, last_name, department, position, profile_photo,
        (SELECT COUNT(*) FROM staff_doctor_chat WHERE doctor_id = $doctor_id AND staff_id = s.staff_id AND sender = 'staff' AND is_read = 0) as unread
    FROM staff s
    WHERE status = 'active'
    ORDER BY first_name
");

// Get messages for selected staff
$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, position, profile_photo FROM staff WHERE staff_id = $staff_id")->fetch_assoc();
    $messages = $conn->query("SELECT * FROM staff_doctor_chat WHERE doctor_id = $doctor_id AND staff_id = $staff_id ORDER BY created_at ASC");
    $conn->query("UPDATE staff_doctor_chat SET is_read = 1 WHERE doctor_id = $doctor_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_doctor_chat (staff_id, doctor_id, message, sender) VALUES (?, ?, ?, 'doctor')");
    $stmt->bind_param("iis", $staff_id, $doctor_id, $message);
    $stmt->execute();
    header("Location: staff_chat.php?staff_id=$staff_id");
    exit();
}

function getProfilePic($photo, $name) {
    if (!empty($photo) && file_exists("../" . $photo)) {
        return "../" . $photo;
    }
    return "https://ui-avatars.com/api/?background=0f6b4c&color=fff&name=" . urlencode($name);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Doctor-Staff Chat</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: 450px; overflow-y: auto; padding: 15px; background: #f9f9f9; border-radius: 15px; }
        .message-doctor { text-align: right; margin-bottom: 15px; }
        .message-doctor .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; text-decoration: none; display: block; }
        .chat-item:hover { background: #f0fdf4; }
        .chat-item.active { background: #f0fdf4; border-left: 4px solid #0f6b4c; }
        .chat-avatar { width: 45px; height: 45px; border-radius: 50%; object-fit: cover; margin-right: 12px; }
        .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-headset"></i> Hospital Staff Chat</span>
        <div><span class="text-white me-2">Dr. <?= htmlspecialchars($doctor_name) ?></span><a href="dashboard.php" class="btn btn-light btn-sm">Back</a></div>
    </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">Hospital Staff</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()): ?>
                <a href="?staff_id=<?= $s['staff_id'] ?>" class="chat-item <?= (isset($_GET['staff_id']) && $_GET['staff_id'] == $s['staff_id']) ? 'active' : '' ?>">
                    <div class="d-flex align-items-center">
                        <img src="<?= getProfilePic($s['profile_photo'], $s['first_name'].' '.$s['last_name']) ?>" class="chat-avatar">
                        <div class="flex-grow-1">
                            <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"><?= ucfirst($s['department']) ?> - <?= ucfirst($s['position']) ?></small>
                        </div>
                    </div>
                </a>
            <?php endwhile; ?>
        <?php else: ?><div class="p-3 text-muted">No staff found.</div><?php endif; ?>
    </div></div></div>
    <div class="col-md-8"><div class="card h-100"><div class="card-header bg-primary text-white">
        <h6><?php if($selected_staff): ?><img src="<?= getProfilePic($selected_staff['profile_photo'], $selected_staff['first_name'].' '.$selected_staff['last_name']) ?>" style="width:30px;height:30px;border-radius:50%;margin-right:8px;"> <?= htmlspecialchars($selected_staff['first_name'].' '.$selected_staff['last_name']) ?> (<?= ucfirst($selected_staff['department']) ?>)<?php else: ?>Select a staff member<?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'] == 'doctor') ? 'doctor' : '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" 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>