<?php
/**
 * ===================================================================================
 * Teacher Inbox Page (Mobile Responsive & Threaded)
 * ===================================================================================
 *
 * File: inbox.php
 * Location: /homework_portal/teacher/inbox.php
 *
 * Purpose:
 * 1. Displays messages from the admin in conversation threads.
 * 2. Provides a "Reply" button on admin messages.
 * 3. Adapts to mobile, tablet, and desktop screens.
 */

require_once '../config.php';

// --- Security Check ---
if (!isset($_SESSION['teacher_id'])) {
    header('Location: login.php');
    exit();
}

$teacher_id = $_SESSION['teacher_id'];
$teacher_full_name = e($_SESSION['teacher_full_name'] ?? 'Teacher');

// --- Handle feedback messages from session ---
$success_message = '';
$error_message = '';
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}
if (isset($_SESSION['error_message'])) {
    $error_message = $_SESSION['error_message'];
    unset($_SESSION['error_message']);
}


try {
    // Fetch all messages related to this teacher, ordered to group conversations.
    $sql = "
        SELECT 
            tm.id, tm.title, tm.message, tm.created_at, tm.sender_type, tm.is_read, tm.file_path,
            COALESCE(tm.parent_message_id, tm.id) as thread_id
        FROM teacher_messages tm
        WHERE tm.teacher_id = ?
        ORDER BY thread_id DESC, tm.created_at ASC
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$teacher_id]);
    $all_messages = $stmt->fetchAll();

    // Group messages into threads
    $threads = [];
    foreach ($all_messages as $message) {
        $threads[$message['thread_id']][] = $message;
    }

    // Mark all unread messages FROM THE ADMIN as read
    $update_sql = "UPDATE teacher_messages SET is_read = 1 WHERE teacher_id = ? AND is_read = 0 AND sender_type = 'admin'";
    $pdo->prepare($update_sql)->execute([$teacher_id]);

    // Fetch submission count for the sidebar badge
    $new_submission_sql = "
        SELECT COUNT(sub.id) 
        FROM submissions sub
        JOIN assignments a ON sub.assignment_id = a.id
        LEFT JOIN teacher_seen_submissions tss ON sub.id = tss.submission_id AND tss.teacher_id = ?
        WHERE a.teacher_id = ? AND tss.submission_id IS NULL
    ";
    $new_submission_stmt = $pdo->prepare($new_submission_sql);
    $new_submission_stmt->execute([$teacher_id, $teacher_id]);
    $new_submission_count = $new_submission_stmt->fetchColumn();

    // Unread message count will now be 0 for the badge
    $unread_messages_count = 0;


} catch (PDOException $e) {
    $threads = [];
    $new_submission_count = 0;
    $unread_messages_count = 0;
    $page_error = "Could not load your messages.";
    error_log($e->getMessage());
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Inbox - Teacher Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&family=Baloo+2:wght@700&display=swap" rel="stylesheet">
    <style>
        body { font-family: 'Poppins', sans-serif; background-color: #f0f9ff; }
        .font-brand { font-family: 'Baloo 2', cursive; }
        .sidebar-link { display: flex; align-items: center; padding: 0.75rem 1rem; border-radius: 0.5rem; font-weight: 500;}
        .sidebar-link:hover, .sidebar-link.active { background-color: #e0f2fe; color: #0284c7; font-weight: 600; }
        .notification-badge { display: inline-flex; align-items: center; justify-content: center; min-width: 22px; height: 22px; padding: 0 4px; border-radius: 9999px; background-color: #ef4444; color: white; font-size: 0.75rem; font-weight: bold; }
        .message.admin { background-color: #eff6ff; border-color: #3b82f6; } /* Blue for admin messages */
        .message.teacher { background-color: #f0fdfa; border-color: #14b8a6; } /* Teal for teacher replies */
    </style>
</head>
<body class="flex flex-col min-h-screen">
    <div class="relative min-h-screen md:flex">
        <!-- Mobile menu button -->
        <div class="md:hidden flex justify-between items-center bg-white p-4 shadow-md">
             <a href="dashboard.php">
                <h1 class="text-3xl font-bold text-red-600 font-sans">TTTEDDDEL</h1>
            </a>
            <button id="mobile-menu-button" class="text-gray-500 hover:text-blue-600 focus:outline-none">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16m-7 6h7"></path></svg>
            </button>
        </div>

        <!-- Sidebar Navigation -->
        <aside id="sidebar" class="w-64 bg-white shadow-md absolute inset-y-0 left-0 transform -translate-x-full md:relative md:translate-x-0 transition-transform duration-300 ease-in-out z-30">
            <div class="p-4 border-b text-center">
                <a href="dashboard.php">
                    <h1 class="text-4xl font-bold text-red-600 tracking-widest font-sans">TTTEDDDEL</h1>
                    <p class="text-xs font-semibold text-blue-800 mt-1">Teacher-Student Interactive System</p>
                    <p class="text-xs text-blue-800">by Ele Infocomm Technologies</p>
                </a>
            </div>
            <nav class="p-4 space-y-2">
                <a href="dashboard.php" class="sidebar-link"><span>Dashboard</span></a>
                <a href="inbox.php" class="sidebar-link active flex justify-between items-center">
                    <span>Inbox</span>
                    <?php if ($unread_messages_count > 0): ?><span class="notification-badge"><?php echo $unread_messages_count; ?></span><?php endif; ?>
                </a>
                <a href="manage_students.php" class="sidebar-link"><span>My Students</span></a>
                <a href="post_material.php" class="sidebar-link"><span>Post Material</span></a>
                <a href="my_materials.php" class="sidebar-link"><span>My Posted Materials</span></a>
                <a href="view_submissions.php" class="sidebar-link flex justify-between items-center">
                    <span>View Submissions</span>
                     <?php if ($new_submission_count > 0): ?><span class="notification-badge"><?php echo $new_submission_count; ?></span><?php endif; ?>
                </a>
            </nav>
        </aside>

        <!-- Main Content Area -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <header class="bg-white shadow-sm border-b hidden md:flex"><div class="flex items-center justify-end p-4 w-full"><span class="text-gray-600 mr-4">Welcome, <?php echo $teacher_full_name; ?>!</span><a href="../logout.php" class="ml-2 py-2 px-4 bg-teal-600 text-white font-semibold rounded-lg shadow-md hover:bg-teal-700">Logout</a></div></header>
            <main class="flex-1 overflow-x-hidden overflow-y-auto bg-gray-100 p-4 md:p-6">
                <h2 class="text-3xl font-semibold text-gray-800">My Inbox</h2>
                <p class="text-gray-500 mt-1">Conversations with the school admin.</p>
                
                <?php if ($success_message): ?><div class="p-4 my-4 text-sm text-green-800 bg-green-100 rounded-lg"><?php echo e($success_message); ?></div><?php endif; ?>
                <?php if ($error_message): ?><div class="p-4 my-4 text-sm text-red-800 bg-red-100 rounded-lg"><?php echo e($error_message); ?></div><?php endif; ?>
                <?php if (isset($page_error)): ?><div class="p-4 my-4 text-sm text-red-800 bg-red-100 rounded-lg"><?php echo e($page_error); ?></div><?php endif; ?>
                
                <div class="mt-6 space-y-6">
                    <?php if(empty($threads)): ?>
                        <div class="bg-white p-6 rounded-lg shadow text-center text-gray-500">You have no messages.</div>
                    <?php else: ?>
                        <?php foreach($threads as $thread_id => $thread_messages): 
                            $first_message = $thread_messages[0]; ?>
                            <div class="bg-white rounded-lg shadow-md overflow-hidden">
                                <div class="p-4 bg-gray-50 border-b flex flex-col sm:flex-row justify-between items-start sm:items-center">
                                    <h3 class="font-bold text-lg text-gray-800"><?php echo e($first_message['title']); ?></h3>
                                    <a href="reply_message.php?id=<?php echo e($thread_id); ?>" class="mt-2 sm:mt-0 text-sm px-4 py-2 bg-teal-100 text-teal-800 font-semibold rounded-lg hover:bg-teal-200">Reply to this Conversation</a>
                                </div>
                                <div class="p-4 space-y-4">
                                    <?php foreach($thread_messages as $message): ?>
                                        <div class="message p-4 rounded-lg border-l-4 <?php echo $message['sender_type']; ?>">
                                            <div class="flex justify-between items-center text-xs text-gray-500 mb-2">
                                                <span class="font-semibold"><?php echo $message['sender_type'] === 'admin' ? 'Admin' : 'You (Reply)'; ?></span>
                                                <span><?php echo date('M d, Y, g:i a', strtotime($message['created_at'])); ?></span>
                                            </div>
                                            <p class="text-gray-700 break-words"><?php echo nl2br(e($message['message'])); ?></p>
                                            <?php if (!empty($message['file_path'])): ?>
                                                <div class="mt-3">
                                                    <a href="../<?php echo e($message['file_path']); ?>" target="_blank" class="text-sm text-blue-600 hover:underline">
                                                        View Attachment
                                                    </a>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </main>
        </div>
    </div>
    <footer class="text-center py-6 bg-gray-100 border-t mt-auto">
        <p class="text-xs text-gray-500">Built By Ele InfoComm Technologies- Kenya | <a href="http://web.e-ict.co.ke" target="_blank" class="hover:underline">web.e-ict.co.ke</a> | <a href="mailto:info@e-ict.co.ke" class="hover:underline">info@e-ict.co.ke</a> | +254202000121 | +254 722 215810 | 2025 All right reserved.</p>
    </footer>

    <script>
        const btn = document.getElementById('mobile-menu-button');
        const sidebar = document.getElementById('sidebar');

        btn.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
        });
    </script>
</body>
</html>
