<?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'];

$conn->query("CREATE TABLE IF NOT EXISTS nurse_doctor_chat (
    id INT AUTO_INCREMENT PRIMARY KEY,
    nurse_id INT NOT NULL,
    doctor_id INT NOT NULL,
    message TEXT NOT NULL,
    sender ENUM('nurse','doctor') DEFAULT 'nurse',
    is_read TINYINT(1) DEFAULT 0,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)");

$all_nurses = $conn->query("
    SELECT nurse_id, first_name, last_name, specialization, ward, profile_photo,
        (SELECT COUNT(*) FROM nurse_doctor_chat WHERE doctor_id = $doctor_id AND nurse_id = n.nurse_id AND sender = 'nurse' AND is_read = 0) as unread
    FROM nurses n
    WHERE status = 'active'
    ORDER BY first_name
");

$selected_nurse = null;
$messages = null;
if (isset($_GET['nurse_id'])) {
    $nurse_id = (int)$_GET['nurse_id'];
    $selected_nurse = $conn->query("SELECT nurse_id, first_name, last_name, specialization, ward, profile_photo FROM nurses WHERE nurse_id = $nurse_id")->fetch_assoc();
    $messages = $conn->query("SELECT * FROM nurse_doctor_chat WHERE doctor_id = $doctor_id AND nurse_id = $nurse_id ORDER BY created_at ASC");
    $conn->query("UPDATE nurse_doctor_chat SET is_read = 1 WHERE doctor_id = $doctor_id AND nurse_id = $nurse_id AND sender = 'nurse'");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $nurse_id = (int)$_POST['nurse_id'];
    $message = $conn->real_escape_string($_POST['message']);
    $stmt = $conn->prepare("INSERT INTO nurse_doctor_chat (nurse_id, doctor_id, message, sender) VALUES (?, ?, ?, 'doctor')");
    $stmt->bind_param("iis", $nurse_id, $doctor_id, $message);
    $stmt->execute();
    header("Location: nurse_chat.php?nurse_id=$nurse_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><head><title>Nurse 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:20px20px5px20px;max-width:70%;}
.message-nurse{text-align:left;margin-bottom:15px;}.message-nurse .bubble{background:#e9ecef;color:#333;display:inline-block;padding:10px15px;border-radius:20px20px20px5px;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:2px6px;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-user-nurse"></i> Nurse Collaboration</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">Nursing Staff</div><div class="card-body p-0" style="max-height:550px;overflow-y:auto;">
<?php if($all_nurses && $all_nurses->num_rows > 0): ?>
    <?php while($n = $all_nurses->fetch_assoc()): ?>
        <a href="?nurse_id=<?= $n['nurse_id'] ?>" class="chat-item <?= (isset($_GET['nurse_id']) && $_GET['nurse_id'] == $n['nurse_id']) ? 'active' : '' ?>">
            <div class="d-flex align-items-center"><img src="<?= getProfilePic($n['profile_photo'], $n['first_name'].' '.$n['last_name']) ?>" class="chat-avatar"><div class="flex-grow-1"><div class="d-flex justify-content-between"><strong><?= htmlspecialchars($n['first_name'].' '.$n['last_name']) ?></strong><?php if($n['unread'] > 0): ?><span class="unread-badge"><?= $n['unread'] ?></span><?php endif; ?></div><small class="text-muted"><?= htmlspecialchars($n['specialization']) ?> | Ward: <?= htmlspecialchars($n['ward']) ?></small></div></div>
        </a>
    <?php endwhile; ?>
<?php else: ?><div class="p-3 text-muted">No nurses 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_nurse): ?><img src="<?= getProfilePic($selected_nurse['profile_photo'], $selected_nurse['first_name'].' '.$selected_nurse['last_name']) ?>" style="width:30px;height:30px;border-radius:50%;margin-right:8px;"> Nurse <?= htmlspecialchars($selected_nurse['first_name'].' '.$selected_nurse['last_name']) ?> (<?= htmlspecialchars($selected_nurse['specialization']) ?>)<?php else: ?>Select a nurse<?php endif; ?></h6></div>
<div class="card-body p-0 d-flex flex-column" style="height:550px;">
<?php if($selected_nurse): ?>
    <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' : 'nurse' ?>"><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="nurse_id" value="<?= $selected_nurse['nurse_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 nurse 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>