<?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 doctors except self with profile photos
$all_doctors = $conn->query("
    SELECT doctor_id, name, specialization, profile_photo, 
        (SELECT COUNT(*) FROM doctor_doctor_chat WHERE receiver_id = $doctor_id AND sender_id = d.doctor_id AND is_read = 0) as unread
    FROM doctors d
    WHERE doctor_id != $doctor_id AND status = 'active'
    ORDER BY name
");

// Get recent conversations with last message
$conversations = $conn->query("
    SELECT DISTINCT 
        CASE WHEN sender_id = $doctor_id THEN receiver_id ELSE sender_id END as other_doctor_id,
        (SELECT name FROM doctors WHERE doctor_id = other_doctor_id) as other_name,
        (SELECT specialization FROM doctors WHERE doctor_id = other_doctor_id) as other_specialization,
        (SELECT profile_photo FROM doctors WHERE doctor_id = other_doctor_id) as other_photo,
        (SELECT message FROM doctor_doctor_chat 
         WHERE (sender_id = $doctor_id AND receiver_id = other_doctor_id) 
            OR (sender_id = other_doctor_id AND receiver_id = $doctor_id) 
         ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM doctor_doctor_chat 
         WHERE (sender_id = $doctor_id AND receiver_id = other_doctor_id) 
            OR (sender_id = other_doctor_id AND receiver_id = $doctor_id) 
         ORDER BY created_at DESC LIMIT 1) as last_date,
        (SELECT COUNT(*) FROM doctor_doctor_chat 
         WHERE receiver_id = $doctor_id AND sender_id = other_doctor_id AND is_read = 0) as unread
    FROM doctor_doctor_chat
    WHERE sender_id = $doctor_id OR receiver_id = $doctor_id
    GROUP BY other_doctor_id
    ORDER BY last_date DESC
");

// Get messages for selected doctor
$selected_doctor = null;
$messages = null;
if (isset($_GET['chat_with'])) {
    $chat_with = (int)$_GET['chat_with'];
    $selected_doctor = $conn->query("SELECT doctor_id, name, specialization, profile_photo FROM doctors WHERE doctor_id = $chat_with")->fetch_assoc();
    $messages = $conn->query("
        SELECT * FROM doctor_doctor_chat 
        WHERE (sender_id = $doctor_id AND receiver_id = $chat_with) 
           OR (sender_id = $chat_with AND receiver_id = $doctor_id) 
        ORDER BY created_at ASC
    ");
    $conn->query("UPDATE doctor_doctor_chat SET is_read = 1 WHERE receiver_id = $doctor_id AND sender_id = $chat_with");
}

if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['send_message'])) {
    $receiver_id = (int)$_POST['receiver_id'];
    $message = $conn->real_escape_string($_POST['message']);
    $stmt = $conn->prepare("INSERT INTO doctor_doctor_chat (sender_id, receiver_id, message) VALUES (?, ?, ?)");
    $stmt->bind_param("iis", $doctor_id, $receiver_id, $message);
    $stmt->execute();
    header("Location: doctor_chat.php?chat_with=$receiver_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 lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Doctor-to-Doctor Chat - UHD</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); }
        .messages-container { height: 450px; overflow-y: auto; padding: 15px; background: #f9f9f9; border-radius: 15px; }
        .message-me { text-align: right; margin-bottom: 15px; }
        .message-me .bubble { background: #0f6b4c; color: white; display: inline-block; padding: 10px 15px; border-radius: 20px 20px 5px 20px; max-width: 70%; }
        .message-other { text-align: left; margin-bottom: 15px; }
        .message-other .bubble { background: #e9ecef; color: #333; display: inline-block; padding: 10px 15px; border-radius: 20px 20px 20px 5px; 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; }
        .chat-avatar-sm { width: 35px; height: 35px; border-radius: 50%; object-fit: cover; margin-right: 10px; }
        .unread-badge { background: #dc3545; color: white; border-radius: 50%; padding: 2px 6px; font-size: 10px; margin-left: 5px; }
        .online-dot { width: 10px; height: 10px; background: #28a745; border-radius: 50%; display: inline-block; margin-right: 5px; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark">
    <div class="container">
        <span class="navbar-brand"><i class="fas fa-comments"></i> Doctor Collaboration Chat</span>
        <div>
            <span class="text-white me-2"><i class="fas fa-user-md"></i> 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">
        <!-- Doctors List -->
        <div class="col-md-4">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h6 class="mb-0"><i class="fas fa-user-md"></i> Colleagues</h6>
                </div>
                <div class="card-body p-0" style="max-height: 550px; overflow-y: auto;">
                    <?php if($all_doctors && $all_doctors->num_rows > 0): ?>
                        <?php while($d = $all_doctors->fetch_assoc()): ?>
                            <a href="?chat_with=<?= $d['doctor_id'] ?>" class="chat-item <?= (isset($_GET['chat_with']) && $_GET['chat_with'] == $d['doctor_id']) ? 'active' : '' ?>">
                                <div class="d-flex align-items-center">
                                    <img src="<?= getProfilePic($d['profile_photo'], $d['name']) ?>" class="chat-avatar" alt="<?= htmlspecialchars($d['name']) ?>">
                                    <div class="flex-grow-1">
                                        <div class="d-flex justify-content-between">
                                            <strong>Dr. <?= htmlspecialchars($d['name']) ?></strong>
                                            <?php if($d['unread'] > 0): ?>
                                                <span class="unread-badge"><?= $d['unread'] ?></span>
                                            <?php endif; ?>
                                        </div>
                                        <small class="text-muted"><?= htmlspecialchars($d['specialization']) ?></small>
                                    </div>
                                </div>
                            </a>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="p-3 text-muted">No other doctors found.</div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Chat Area -->
        <div class="col-md-8">
            <div class="card h-100">
                <div class="card-header bg-primary text-white">
                    <h6 class="mb-0">
                        <?php if($selected_doctor): ?>
                            <img src="<?= getProfilePic($selected_doctor['profile_photo'], $selected_doctor['name']) ?>" class="chat-avatar-sm" style="width:30px;height:30px;">
                            Dr. <?= htmlspecialchars($selected_doctor['name']) ?> (<?= htmlspecialchars($selected_doctor['specialization']) ?>)
                        <?php else: ?>
                            <i class="fas fa-comments"></i> Select a colleague to chat
                        <?php endif; ?>
                    </h6>
                </div>
                <div class="card-body p-0 d-flex flex-column" style="height: 550px;">
                    <?php if($selected_doctor): ?>
                        <div class="messages-container" id="messagesContainer">
                            <?php if($messages && $messages->num_rows > 0): ?>
                                <?php while($m = $messages->fetch_assoc()): ?>
                                    <div class="message-<?= ($m['sender_id'] == $doctor_id) ? 'me' : 'other' ?>">
                                        <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. Start a conversation with Dr. <?= htmlspecialchars($selected_doctor['name']) ?></p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <form method="POST" class="p-3 border-top">
                            <input type="hidden" name="receiver_id" value="<?= $selected_doctor['doctor_id'] ?>">
                            <div class="input-group">
                                <textarea name="message" class="form-control" rows="2" placeholder="Type your message..." 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 colleague from the left to start chatting.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

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