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

$doctors = $conn->query("SELECT doctor_id, name FROM doctors WHERE doctor_id != $doctor_id ORDER BY name");
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'])) {
    $rec = $_POST['receiver_id'];
    $msg = $conn->real_escape_string($_POST['message']);
    $conn->query("INSERT INTO doctor_chat (sender_id, receiver_id, message) VALUES ($doctor_id, $rec, '$msg')");
}
$messages = [];
if ($receiver) {
    $messages = $conn->query("SELECT * FROM doctor_chat WHERE (sender_id=$doctor_id AND receiver_id=$receiver) OR (sender_id=$receiver AND receiver_id=$doctor_id) ORDER BY created_at");
}
?>
<!DOCTYPE html>
<html><head><title>Doctor Chat</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body><nav class="navbar navbar-dark bg-dark"><div class="container"><span class="navbar-brand">Doctor Social Circle</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">Colleagues</div><ul class="list-group"><?php while($d=$doctors->fetch_assoc()): ?><li class="list-group-item"><a href="?receiver=<?= $d['doctor_id'] ?>">Dr. <?= $d['name'] ?></a></li><?php endwhile; ?></ul></div></div>
<div class="col-md-8"><?php if($receiver): $recName = $conn->query("SELECT name FROM doctors WHERE doctor_id=$receiver")->fetch_assoc()['name']; ?>
<div class="card"><div class="card-header">Chat with Dr. <?= $recName ?></div><div class="card-body"><div id="chatBox" style="height:300px;overflow-y:auto;border:1px solid #ccc;padding:10px;"><?php while($m=$messages->fetch_assoc()): ?><div><strong><?= ($m['sender_id']==$doctor_id?'You':$recName) ?>:</strong> <?= htmlspecialchars($m['message']) ?> <small><?= date('H:i',strtotime($m['created_at'])) ?></small></div><?php endwhile; ?></div>
<form method="POST"><input type="hidden" name="receiver_id" value="<?= $receiver ?>"><div class="input-group mt-2"><input type="text" name="message" class="form-control" required><button class="btn btn-primary">Send</button></div></form></div></div><?php endif; ?></div></div></div>
<script>setTimeout(()=>{let b=document.getElementById('chatBox');if(b)b.scrollTop=b.scrollHeight;},100);</script>
</body>
</html>