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

$staff_id = $_SESSION['staff_id'];
$staff_name = $_SESSION['staff_name'];

// Get all doctors for chat
$doctors = $conn->query("SELECT doctor_id, name, specialization FROM doctors WHERE status = 'active' ORDER BY name");

// Get all patients for chat
$patients = $conn->query("SELECT patient_id, first_name, last_name FROM patients WHERE portal_active = 1 ORDER BY first_name");

// Get recent chats
$recent_doctor_chats = $conn->query("
    SELECT DISTINCT d.doctor_id, d.name, 
        (SELECT message FROM staff_doctor_chat WHERE staff_id = $staff_id AND doctor_id = d.doctor_id ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM staff_doctor_chat WHERE staff_id = $staff_id AND doctor_id = d.doctor_id ORDER BY created_at DESC LIMIT 1) as last_date,
        (SELECT COUNT(*) FROM staff_doctor_chat WHERE staff_id = $staff_id AND doctor_id = d.doctor_id AND sender = 'doctor' AND is_read = 0) as unread
    FROM staff_doctor_chat sdc
    JOIN doctors d ON sdc.doctor_id = d.doctor_id
    WHERE sdc.staff_id = $staff_id
    GROUP BY d.doctor_id
    ORDER BY last_date DESC
");

$recent_patient_chats = $conn->query("
    SELECT DISTINCT p.patient_id, p.first_name, p.last_name,
        (SELECT message FROM staff_patient_chat WHERE staff_id = $staff_id AND patient_id = p.patient_id ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM staff_patient_chat WHERE staff_id = $staff_id AND patient_id = p.patient_id ORDER BY created_at DESC LIMIT 1) as last_date,
        (SELECT COUNT(*) FROM staff_patient_chat WHERE staff_id = $staff_id AND patient_id = p.patient_id AND sender = 'patient' AND is_read = 0) as unread
    FROM staff_patient_chat spc
    JOIN patients p ON spc.patient_id = p.patient_id
    WHERE spc.staff_id = $staff_id
    GROUP BY p.patient_id
    ORDER BY last_date DESC
");

// Get messages for selected chat
$selected_doctor = null;
$selected_patient = null;
$messages = null;
$chat_type = null;

if (isset($_GET['doctor_id'])) {
    $doctor_id = (int)$_GET['doctor_id'];
    $selected_doctor = $conn->query("SELECT doctor_id, name, specialization FROM doctors WHERE doctor_id = $doctor_id")->fetch_assoc();
    $messages = $conn->query("SELECT * FROM staff_doctor_chat WHERE staff_id = $staff_id AND doctor_id = $doctor_id ORDER BY created_at ASC");
    $chat_type = 'doctor';
    // Mark messages as read
    $conn->query("UPDATE staff_doctor_chat SET is_read = 1 WHERE staff_id = $staff_id AND doctor_id = $doctor_id AND sender = 'doctor'");
} elseif (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 staff_patient_chat WHERE staff_id = $staff_id AND patient_id = '$patient_id' ORDER BY created_at ASC");
    $chat_type = 'patient';
    // Mark messages as read
    $conn->query("UPDATE staff_patient_chat SET is_read = 1 WHERE staff_id = $staff_id AND patient_id = '$patient_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>Staff 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); }
        .chat-sidebar { height: 600px; overflow-y: auto; }
        .chat-area { height: 600px; display: flex; flex-direction: column; }
        .messages-container { flex: 1; overflow-y: auto; padding: 15px; background: #f9f9f9; border-radius: 15px; }
        .message-staff { text-align: right; margin-bottom: 15px; }
        .message-staff .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; transition: 0.2s; padding: 12px; border-bottom: 1px solid #eee; }
        .chat-item:hover { background: #f0fdf4; }
        .chat-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; }
        .status-badge { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 5px; }
        .status-online { background: #28a745; }
        .status-offline { background: #6c757d; }
    </style>
</head>
<body>
<nav class="navbar navbar-dark">
    <div class="container">
        <span class="navbar-brand"><i class="fas fa-comments"></i> Staff Communication Hub</span>
        <div>
            <span class="text-white me-2"><i class="fas fa-user-tie"></i> <?= htmlspecialchars($staff_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">
        <!-- Sidebar -->
        <div class="col-md-4">
            <!-- Doctors Section -->
            <div class="card mb-3">
                <div class="card-header bg-success text-white">
                    <h6 class="mb-0"><i class="fas fa-user-md"></i> Doctors</h6>
                </div>
                <div class="chat-sidebar">
                    <?php if($doctors && $doctors->num_rows > 0): ?>
                        <?php 
                        $doctor_list = [];
                        while($d = $doctors->fetch_assoc()) {
                            $doctor_list[] = $d;
                            $unread = $conn->query("SELECT COUNT(*) as cnt FROM staff_doctor_chat WHERE staff_id = $staff_id AND doctor_id = {$d['doctor_id']} AND sender = 'doctor' AND is_read = 0")->fetch_assoc()['cnt'];
                        ?>
                            <a href="?doctor_id=<?= $d['doctor_id'] ?>" class="chat-item d-block text-decoration-none <?= (isset($_GET['doctor_id']) && $_GET['doctor_id'] == $d['doctor_id']) ? 'active' : '' ?>">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <span class="status-badge status-offline"></span>
                                        <strong>Dr. <?= htmlspecialchars($d['name']) ?></strong>
                                        <br><small class="text-muted"><?= htmlspecialchars($d['specialization']) ?></small>
                                    </div>
                                    <?php if($unread > 0): ?>
                                        <span class="unread-badge"><?= $unread ?></span>
                                    <?php endif; ?>
                                </div>
                            </a>
                        <?php } ?>
                    <?php else: ?>
                        <div class="p-3 text-muted">No doctors found.</div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Patients Section -->
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-users"></i> Patients</h6>
                </div>
                <div class="chat-sidebar">
                    <?php if($patients && $patients->num_rows > 0): ?>
                        <?php while($p = $patients->fetch_assoc()): 
                            $unread = $conn->query("SELECT COUNT(*) as cnt FROM staff_patient_chat WHERE staff_id = $staff_id AND patient_id = '{$p['patient_id']}' AND sender = 'patient' AND is_read = 0")->fetch_assoc()['cnt'];
                        ?>
                            <a href="?patient_id=<?= $p['patient_id'] ?>" class="chat-item d-block text-decoration-none <?= (isset($_GET['patient_id']) && $_GET['patient_id'] == $p['patient_id']) ? 'active' : '' ?>">
                                <div class="d-flex justify-content-between align-items-center">
                                    <div>
                                        <i class="fas fa-user-circle"></i>
                                        <strong><?= htmlspecialchars($p['first_name'] . ' ' . $p['last_name']) ?></strong>
                                    </div>
                                    <?php if($unread > 0): ?>
                                        <span class="unread-badge"><?= $unread ?></span>
                                    <?php endif; ?>
                                </div>
                            </a>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="p-3 text-muted">No patients 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): ?>
                            <i class="fas fa-user-md"></i> Chat with Dr. <?= htmlspecialchars($selected_doctor['name']) ?>
                        <?php elseif($selected_patient): ?>
                            <i class="fas fa-user-circle"></i> Chat with <?= htmlspecialchars($selected_patient['first_name'] . ' ' . $selected_patient['last_name']) ?>
                        <?php else: ?>
                            <i class="fas fa-comments"></i> Select a conversation
                        <?php endif; ?>
                    </h6>
                </div>
                <div class="card-body p-0 d-flex flex-column" style="height: 550px;">
                    <?php if($selected_doctor || $selected_patient): ?>
                        <div class="messages-container" id="messagesContainer">
                            <?php if($messages && $messages->num_rows > 0): ?>
                                <?php while($m = $messages->fetch_assoc()): ?>
                                    <div class="message-<?= ($m['sender'] == 'staff') ? 'staff' : '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. Send a message to start the conversation.</p>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <!-- Message Input -->
                        <form action="send_chat.php" method="POST" class="p-3 border-top">
                            <input type="hidden" name="chat_type" value="<?= $chat_type ?>">
                            <?php if($selected_doctor): ?>
                                <input type="hidden" name="doctor_id" value="<?= $selected_doctor['doctor_id'] ?>">
                            <?php elseif($selected_patient): ?>
                                <input type="hidden" name="patient_id" value="<?= $selected_patient['patient_id'] ?>">
                            <?php endif; ?>
                            <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 doctor or patient from the left to start chatting.</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // Auto-scroll to bottom
    var container = document.getElementById('messagesContainer');
    if (container) {
        container.scrollTop = container.scrollHeight;
    }
    
    // Refresh page every 10 seconds for new messages (optional)
    setTimeout(function() {
        location.reload();
    }, 30000);
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>