<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

$user_id = $_SESSION['patient_id'];
$user_name = $_SESSION['patient_name'];

// Get all conversations with doctors
$conversations = $conn->query("
    SELECT DISTINCT 
        d.doctor_id,
        d.name as doctor_name,
        d.specialization,
        (SELECT message FROM patient_doctor_messages 
         WHERE doctor_id = d.doctor_id AND patient_id = '$user_id' 
         ORDER BY created_at DESC LIMIT 1) as last_message,
        (SELECT created_at FROM patient_doctor_messages 
         WHERE doctor_id = d.doctor_id AND patient_id = '$user_id' 
         ORDER BY created_at DESC LIMIT 1) as last_time,
        (SELECT COUNT(*) FROM patient_doctor_messages 
         WHERE doctor_id = d.doctor_id AND patient_id = '$user_id' AND is_read = 0 AND sender = 'doctor') as unread_count
    FROM patient_doctor_messages pdm
    JOIN doctors d ON pdm.doctor_id = d.doctor_id
    WHERE pdm.patient_id = '$user_id'
    GROUP BY d.doctor_id
    ORDER BY last_time DESC
");

// If no conversations, show all available doctors
if ($conversations->num_rows == 0) {
    $conversations = $conn->query("
        SELECT doctor_id, name as doctor_name, specialization 
        FROM doctors 
        WHERE status = 'active'
        ORDER BY name ASC
    ");
}

$page_title = 'Messages | UHD';
include '../include/header.php';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Messages - 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: linear-gradient(135deg, #0a3d2f, #064e3b); font-family: 'Segoe UI', sans-serif; }
        
        .messages-container {
            background: white;
            border-radius: 24px;
            overflow: hidden;
            margin-top: 20px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        .conversation-list {
            border-right: 1px solid #e0e0e0;
            height: 550px;
            overflow-y: auto;
        }
        
        .chat-area {
            height: 550px;
            display: flex;
            flex-direction: column;
            background: #f8f9fa;
        }
        
        .conversation-item {
            padding: 15px;
            border-bottom: 1px solid #e0e0e0;
            cursor: pointer;
            transition: all 0.2s;
        }
        
        .conversation-item:hover {
            background: #f0fdf4;
        }
        
        .conversation-item.active {
            background: #e8f5e9;
            border-left: 4px solid #d4a017;
        }
        
        .doctor-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #0a3d2f;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: bold;
            font-size: 1.2rem;
        }
        
        .unread-badge {
            background: #dc3545;
            color: white;
            border-radius: 30px;
            padding: 2px 8px;
            font-size: 0.7rem;
            margin-left: 8px;
        }
        
        .chat-header {
            background: white;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }
        
        .message {
            margin-bottom: 15px;
            display: flex;
        }
        
        .message.sent {
            justify-content: flex-end;
        }
        
        .message.received {
            justify-content: flex-start;
        }
        
        .message-bubble {
            max-width: 70%;
            padding: 10px 15px;
            border-radius: 18px;
        }
        
        .message.sent .message-bubble {
            background: #d4a017;
            color: white;
            border-bottom-right-radius: 4px;
        }
        
        .message.received .message-bubble {
            background: white;
            border: 1px solid #e0e0e0;
            color: #333;
            border-bottom-left-radius: 4px;
        }
        
        .message-time {
            font-size: 0.7rem;
            margin-top: 5px;
            opacity: 0.7;
        }
        
        .chat-input-area {
            background: white;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
        }
        
        .btn-send {
            background: #d4a017;
            color: #0a3d2f;
            border: none;
            border-radius: 30px;
            padding: 8px 20px;
        }
        
        .btn-send:hover {
            background: #b8860b;
            color: white;
        }
        
        @media (max-width: 768px) {
            .conversation-list { height: 400px; }
            .chat-area { height: 450px; }
        }
    </style>
</head>
<body>

<div class="container mt-4">
    <div class="d-flex justify-content-between align-items-center mb-3">
        <h2 class="text-white"><i class="fas fa-comments me-2"></i> Messages</h2>
        <a href="dashboard.php" class="btn btn-outline-light rounded-pill">← Back to Dashboard</a>
    </div>

    <div class="messages-container">
        <div class="row g-0">
            <!-- Conversations List -->
            <div class="col-md-4">
                <div class="conversation-list">
                    <div class="p-3 bg-light border-bottom">
                        <h6 class="mb-0"><i class="fas fa-user-md me-2"></i> Conversations</h6>
                    </div>
                    <?php if ($conversations && $conversations->num_rows > 0): ?>
                        <?php while($conv = $conversations->fetch_assoc()): ?>
                            <div class="conversation-item" onclick="loadChat(<?= $conv['doctor_id'] ?>, '<?= addslashes($conv['doctor_name']) ?>')">
                                <div class="d-flex gap-3">
                                    <div class="doctor-avatar">
                                        <?= strtoupper(substr($conv['doctor_name'], 0, 1)) ?>
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="fw-bold">Dr. <?= htmlspecialchars($conv['doctor_name']) ?></div>
                                        <small class="text-muted"><?= htmlspecialchars($conv['specialization'] ?? 'General') ?></small>
                                        <?php if (isset($conv['last_message'])): ?>
                                            <div class="small text-muted mt-1"><?= htmlspecialchars(substr($conv['last_message'], 0, 40)) ?>...</div>
                                        <?php endif; ?>
                                    </div>
                                    <?php if (isset($conv['unread_count']) && $conv['unread_count'] > 0): ?>
                                        <div class="unread-badge"><?= $conv['unread_count'] ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    <?php else: ?>
                        <div class="text-center py-5">
                            <i class="fas fa-comment-slash fa-3x text-muted mb-2"></i>
                            <p class="text-muted">No conversations yet</p>
                            <p class="small text-muted">When you message a doctor, it will appear here</p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Chat Area -->
            <div class="col-md-8">
                <div class="chat-area">
                    <div class="chat-header" id="chatHeader" style="display: none;">
                        <div class="d-flex align-items-center gap-3">
                            <div class="doctor-avatar" id="chatDoctorAvatar">D</div>
                            <div>
                                <h6 class="mb-0" id="chatDoctorName">Doctor Name</h6>
                                <small class="text-muted" id="chatDoctorSpecialization">Specialization</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="chat-messages" id="chatMessages">
                        <div class="text-center text-muted py-5">
                            <i class="fas fa-comment-dots fa-3x mb-2"></i>
                            <p>Select a conversation to start chatting</p>
                        </div>
                    </div>
                    
                    <div class="chat-input-area" style="display: none;" id="chatInputArea">
                        <div class="input-group">
                            <input type="text" class="form-control" id="messageInput" placeholder="Type your message..." onkeypress="if(event.key==='Enter') sendMessage()">
                            <button class="btn-send" onclick="sendMessage()">
                                <i class="fas fa-paper-plane"></i> Send
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
let currentDoctorId = null;

function loadChat(doctorId, doctorName) {
    currentDoctorId = doctorId;
    
    // Update active state
    $('.conversation-item').removeClass('active');
    $(event.currentTarget).addClass('active');
    
    // Update chat header
    $('#chatHeader').show();
    $('#chatDoctorName').text('Dr. ' + doctorName);
    $('#chatDoctorAvatar').text(doctorName.charAt(0).toUpperCase());
    $('#chatInputArea').show();
    
    // Load messages
    loadMessages(doctorId);
}

function loadMessages(doctorId) {
    $.ajax({
        url: 'ajax_get_messages.php',
        method: 'POST',
        data: { doctor_id: doctorId },
        success: function(response) {
            $('#chatMessages').html(response);
            scrollToBottom();
        },
        error: function() {
            $('#chatMessages').html('<div class="text-center text-muted py-5">Unable to load messages. Please try again.</div>');
        }
    });
}

function sendMessage() {
    let message = $('#messageInput').val().trim();
    if (message === '' || !currentDoctorId) return;
    
    $.ajax({
        url: 'ajax_send_message.php',
        method: 'POST',
        data: {
            doctor_id: currentDoctorId,
            message: message
        },
        success: function(response) {
            $('#messageInput').val('');
            loadMessages(currentDoctorId);
        }
    });
}

function scrollToBottom() {
    let chatMessages = document.getElementById('chatMessages');
    chatMessages.scrollTop = chatMessages.scrollHeight;
}
</script>

<?php include '../include/footer.php'; ?>