<?php
require_once __DIR__ . '/../../includes/dashboard-config.php';

// For role-specific pages, add:
checkRoleAccess(ROLE_STUDENT); // or ROLE_COUNSELOR or ROLE_ADMIN
require_once '../../includes/config.php';
require_once '../../includes/auth.php';
require_once '../../includes/functions.php';

if (!isLoggedIn() || !hasRole('counselor')) {
    header('Location: ../login.php');
    exit();
}

$counselor_id = $_SESSION['user_id'];

// Handle new message
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['send_message'])) {
    $student_id = $_POST['student_id'];
    $subject = $_POST['subject'];
    $content = $_POST['content'];
    
    try {
        $stmt = $pdo->prepare("INSERT INTO messages (sender_id, receiver_id, subject, content) VALUES (?, ?, ?, ?)");
        $stmt->execute([$counselor_id, $student_id, $subject, $content]);
        
        $_SESSION['success_message'] = "Message sent successfully!";
        header("Location: messages.php");
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "Error sending message: " . $e->getMessage();
    }
}

// Get conversations
$conversations = $pdo->prepare("
    SELECT s.id as student_id, s.first_name, s.last_name, s.profile_photo,
           (SELECT COUNT(*) FROM messages WHERE receiver_id = ? AND sender_id = s.id AND is_read = 0) as unread_count,
           MAX(m.created_at) as last_message_time
    FROM students s
    JOIN messages m ON s.id = m.sender_id
    WHERE s.assigned_counselor_id = ? AND m.receiver_id = ?
    GROUP BY s.id
    ORDER BY last_message_time DESC
");
$conversations->execute([$counselor_id, $counselor_id, $counselor_id]);

// Get assigned students for dropdown
$students = $pdo->prepare("
    SELECT id, first_name, last_name 
    FROM students 
    WHERE assigned_counselor_id = ?
    ORDER BY first_name
");
$students->execute([$counselor_id]);

include '../../includes/header.php';
?>

<div class="container py-5">
    <h2 class="mb-4">Student Communications</h2>
    
    <?php displayMessages(); ?>
    
    <div class="row">
        <div class="col-lg-4">
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0">Conversations</h5>
                </div>
                <div class="card-body p-0">
                    <?php if ($conversations->rowCount() > 0): ?>
                        <div class="list-group list-group-flush">
                            <?php while ($conv = $conversations->fetch()): ?>
                                <a href="?student_id=<?= $conv['student_id'] ?>" 
                                   class="list-group-item list-group-item-action <?= isset($_GET['student_id']) && $_GET['student_id'] == $conv['student_id'] ? 'active' : '' ?>">
                                    <div class="d-flex align-items-center">
                                        <img src="../../<?= $conv['profile_photo'] ? 'uploads/profile-photos/'.$conv['profile_photo'] : 'assets/images/default-profile.jpg' ?>" 
                                             class="rounded-circle mr-3" width="40" height="40">
                                        <div>
                                            <h6 class="mb-0"><?= htmlspecialchars($conv['first_name'].' '.$conv['last_name']) ?></h6>
                                            <small class="text-muted">Last message: <?= date('M j, g:i a', strtotime($conv['last_message_time'])) ?></small>
                                        </div>
                                        <?php if ($conv['unread_count'] > 0): ?>
                                            <span class="badge badge-danger ml-auto"><?= $conv['unread_count'] ?></span>
                                        <?php endif; ?>
                                    </div>
                                </a>
                            <?php endwhile; ?>
                        </div>
                    <?php else: ?>
                        <div class="p-3 text-center text-muted">
                            No conversations yet
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">New Message</h5>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="form-group">
                            <label for="student_id">To</label>
                            <select class="form-control" id="student_id" name="student_id" required>
                                <option value="">Select student</option>
                                <?php while ($student = $students->fetch()): ?>
                                    <option value="<?= $student['id'] ?>">
                                        <?= htmlspecialchars($student['first_name'].' '.$student['last_name']) ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="subject">Subject</label>
                            <input type="text" class="form-control" id="subject" name="subject" required>
                        </div>
                        <div class="form-group">
                            <label for="content">Message</label>
                            <textarea class="form-control" id="content" name="content" rows="4" required></textarea>
                        </div>
                        <button type="submit" name="send_message" class="btn btn-primary">Send Message</button>
                    </form>
                </div>
            </div>
        </div>
        
        <div class="col-lg-8">
            <?php if (isset($_GET['student_id'])): ?>
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">Conversation with 
                            <?php 
                            $current_student = $pdo->prepare("SELECT first_name, last_name FROM students WHERE id = ?");
                            $current_student->execute([$_GET['student_id']]);
                            $student = $current_student->fetch();
                            echo htmlspecialchars($student['first_name'].' '.$student['last_name']);
                            ?>
                        </h5>
                    </div>
                    <div class="card-body">
                        <?php
                        // Get messages for this conversation
                        $messages = $pdo->prepare("
                            SELECT m.*, 
                                   CASE WHEN m.sender_id = ? THEN 'sent' ELSE 'received' END as message_type
                            FROM messages m
                            WHERE (m.sender_id = ? AND m.receiver_id = ?)
                            OR (m.sender_id = ? AND m.receiver_id = ?)
                            ORDER BY m.created_at
                        ");
                        $messages->execute([$counselor_id, $counselor_id, $_GET['student_id'], $_GET['student_id'], $counselor_id]);
                        
                        // Mark messages as read
                        $pdo->prepare("UPDATE messages SET is_read = 1, read_at = NOW() 
                                       WHERE receiver_id = ? AND sender_id = ? AND is_read = 0")
                            ->execute([$counselor_id, $_GET['student_id']]);
                        ?>
                        
                        <div class="message-container" style="max-height: 500px; overflow-y: auto;">
                            <?php if ($messages->rowCount() > 0): ?>
                                <?php while ($msg = $messages->fetch()): ?>
                                    <div class="mb-3">
                                        <div class="d-flex <?= $msg['message_type'] == 'sent' ? 'justify-content-end' : '' ?>">
                                            <div class="message-bubble <?= $msg['message_type'] == 'sent' ? 'bg-primary text-white' : 'bg-light' ?>" 
                                                 style="max-width: 70%; padding: 10px 15px; border-radius: 18px;">
                                                <?php if ($msg['message_type'] == 'received'): ?>
                                                    <small class="text-muted d-block">
                                                        <?= date('M j, g:i a', strtotime($msg['created_at'])) ?>
                                                    </small>
                                                <?php endif; ?>
                                                <?= nl2br(htmlspecialchars($msg['content'])) ?>
                                                <?php if ($msg['message_type'] == 'sent'): ?>
                                                    <small class="d-block text-right">
                                                        <?= date('M j, g:i a', strtotime($msg['created_at'])) ?>
                                                        <?php if ($msg['is_read']): ?>
                                                            <i class="fas fa-check-double text-info ml-1"></i>
                                                        <?php else: ?>
                                                            <i class="fas fa-check text-muted ml-1"></i>
                                                        <?php endif; ?>
                                                    </small>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <div class="text-center text-muted py-4">
                                    No messages yet. Start the conversation!
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <form method="post" class="mt-3">
                            <input type="hidden" name="student_id" value="<?= $_GET['student_id'] ?>">
                            <div class="form-group">
                                <textarea class="form-control" name="content" rows="3" placeholder="Type your message..." required></textarea>
                            </div>
                            <button type="submit" name="send_message" class="btn btn-primary">Send</button>
                        </form>
                    </div>
                </div>
            <?php else: ?>
                <div class="text-center py-5">
                    <i class="fas fa-comments fa-4x text-muted mb-3"></i>
                    <h4>Select a conversation</h4>
                    <p class="text-muted">Choose a student from the list to view messages</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<style>
.message-bubble {
    position: relative;
}
.message-bubble.bg-primary:after {
    content: '';
    position: absolute;
    right: -10px;
    top: 10px;
    border-width: 10px 0 10px 10px;
    border-style: solid;
    border-color: transparent #007bff;
}
.message-bubble.bg-light:after {
    content: '';
    position: absolute;
    left: -10px;
    top: 10px;
    border-width: 10px 10px 10px 0;
    border-style: solid;
    border-color: transparent #f8f9fa;
}
</style>

<script>
// Scroll to bottom of messages
const messageContainer = document.querySelector('.message-container');
if (messageContainer) {
    messageContainer.scrollTop = messageContainer.scrollHeight;
}
</script>

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