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

$user_id = $_SESSION['patient_id'];
$doctor_id = $_POST['doctor_id'];

$messages = $conn->query("
    SELECT * FROM patient_doctor_messages 
    WHERE patient_id = '$user_id' AND doctor_id = '$doctor_id'
    ORDER BY created_at ASC
");

if ($messages && $messages->num_rows > 0) {
    while($msg = $messages->fetch_assoc()):
        $is_sent = ($msg['sender'] == 'patient');
?>
        <div class="message <?= $is_sent ? 'sent' : 'received' ?>">
            <div class="message-bubble">
                <?= nl2br(htmlspecialchars($msg['message'])) ?>
                <div class="message-time">
                    <?= date('h:i A', strtotime($msg['created_at'])) ?>
                </div>
            </div>
        </div>
<?php
    endwhile;
} else {
    echo '<div class="text-center text-muted py-5">No messages yet. Start a conversation!</div>';
}
?>