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

// Get all patients assigned to this doctor (from appointments)
$patients = $conn->query("
    SELECT DISTINCT p.patient_id, p.first_name, p.last_name
    FROM appointments a
    JOIN patients p ON a.patient_id = p.patient_id
    WHERE a.doctor_id = $doctor_id AND a.status = 'confirmed'
    ORDER BY p.first_name
");

// Get messages for selected patient
$selected_patient = null;
$messages = null;
if (isset($_GET['patient_id'])) {
    $patient_id = $_GET['patient_id'];
    $selected_patient = $conn->query("SELECT patient_id, first_name, last_name FROM patients WHERE patient_id = '$patient_id'")->fetch_assoc();
    $messages = $conn->query("SELECT * FROM patient_doctor_messages WHERE patient_id = '$patient_id' AND doctor_id = $doctor_id ORDER BY created_at ASC");
    
    // Mark messages as read
    $conn->query("UPDATE patient_doctor_messages SET is_read = 1 WHERE patient_id = '$patient_id' AND doctor_id = $doctor_id AND sender = 'patient'");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Patient Messages - Doctor</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; font-family: 'Segoe UI', sans-serif; }
        .navbar { background: #064e3b !important; }
        .card { border-radius: 20px; background: rgba(255,255,255,0.95); }
        .message-list { height: 400px; 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-patient { text-align: left; margin-bottom: 15px; }
        .message-patient .bubble { background: #e9ecef; color: #333; display: inline-block; padding: 10px 15px; border-radius: 20px 20px 20px 5px; max-width: 70%; }
        .conversation-item { cursor: pointer; transition: 0.2s; text-decoration: none; display: block; }
        .conversation-item:hover { background: #f0fdf4; }
        .conversation-item.active { background: #f0fdf4; border-left: 4px solid #0f6b4c; }
        .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-comments"></i> Patient Messages</span>
        <a href="dashboard.php" class="btn btn-light btn-sm">Back</a>
    </div>
</nav>

<div class="container mt-4">
    <div class="row">
        <!-- Patients List -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h6 class="mb-0">Your Patients</h6>
                </div>
                <div class="card-body p-0">
                    <?php if($patients && $patients->num_rows > 0): ?>
                        <?php while($p = $patients->fetch_assoc()): 
                            // Get unread count for this patient
                            $unread = $conn->query("SELECT COUNT(*) as cnt FROM patient_doctor_messages WHERE patient_id = '{$p['patient_id']}' AND doctor_id = $doctor_id AND sender = 'patient' AND is_read = 0")->fetch_assoc()['cnt'];
                        ?>
                            <a href="?patient_id=<?= $p['patient_id'] ?>" class="conversation-item p-3 border-bottom <?= (isset($_GET['patient_id']) && $_GET['patient_id'] == $p['patient_id']) ? 'active' : '' ?>">
                                <div class="d-flex justify-content-between">
                                    <strong><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></strong>
                                    <?php if($unread > 0): ?>
                                        <span class="unread-badge"><?= $unread ?></span>
                                    <?php endif; ?>
                                </div>
                                <small class="text-muted">Click to start chatting</small>
                            </a>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="p-3 text-center text-muted">No patients assigned yet.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Chat Area -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0">
                        <?php if($selected_patient): ?>
                            <i class="fas fa-user-circle"></i> <?= htmlspecialchars($selected_patient['first_name'] . ' ' . $selected_patient['last_name']) ?>
                        <?php else: ?>
                            Select a patient
                        <?php endif; ?>
                    </h6>
                </div>
                <div class="card-body">
                    <?php if($selected_patient): ?>
                        <div class="message-list" id="messageList">
                            <?php if($messages && $messages->num_rows > 0): ?>
                                <?php while($m = $messages->fetch_assoc()): ?>
                                    <div class="message-<?= $m['sender'] ?>">
                                        <div class="bubble">
                                            <?= nl2br(htmlspecialchars($m['message'])) ?>
                                            <div class="small mt-1 opacity-50"><?= date('h:i A', strtotime($m['created_at'])) ?></div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center text-muted py-5">
                                    <i class="fas fa-comment-dots fa-3x mb-3"></i>
                                    <p>No messages yet. Send a message to start the conversation.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Reply Form -->
                        <form action="reply_chat_message.php" method="POST" class="mt-3">
                            <input type="hidden" name="patient_id" value="<?= $selected_patient['patient_id'] ?>">
                            <div class="input-group">
                                <textarea name="message" class="form-control" rows="2" placeholder="Type your reply..." required></textarea>
                                <button type="submit" name="reply_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-3x mb-3"></i>
                            <p>Select a patient from the left to start messaging.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    var messageList = document.getElementById('messageList');
    if (messageList) {
        messageList.scrollTop = messageList.scrollHeight;
    }
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>