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

$chats = $conn->query("
    SELECT c.*, s.first_name as staff_first, s.last_name as staff_last, d.name as doctor_name 
    FROM staff_doctor_chat c
    LEFT JOIN staff s ON c.staff_id = s.staff_id
    LEFT JOIN doctors d ON c.doctor_id = d.doctor_id
    ORDER BY c.created_at DESC
");
?>
<!DOCTYPE html>
<html>
<head><title>Staff-Doctor Chats</title><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet"></head>
<body>
<div class="container mt-4">
    <h2>Staff-Doctor Conversations</h2>
    <table class="table table-bordered">
        <thead><tr><th>From</th><th>To</th><th>Message</th><th>Date</th><th>Read</th></tr></thead>
        <tbody>
        <?php while($c = $chats->fetch_assoc()): ?>
        <tr>
            <td><?= $c['sender'] == 'staff' ? $c['staff_first'].' '.$c['staff_last'] : 'Dr. '.$c['doctor_name'] ?></td>
            <td><?= $c['sender'] == 'staff' ? 'Dr. '.$c['doctor_name'] : $c['staff_first'].' '.$c['staff_last'] ?></td>
            <td><?= htmlspecialchars($c['message']) ?></td>
            <td><?= date('M d, H:i', strtotime($c['created_at'])) ?></td>
            <td><?= $c['is_read'] ? 'Yes' : 'No' ?></td>
        </tr>
        <?php endwhile; ?>
        </tbody>
    </table>
    <a href="dashboard.php" class="btn btn-secondary">Back</a>
</div>
</body>
</html>