<?php
/**
 * ===================================================================================
 * View Submissions Page (Mobile Responsive)
 * ===================================================================================
 *
 * File: view_submissions.php
 * Location: /homework_portal/teacher/view_submissions.php
 *
 * Purpose:
 * 1. Displays all student submissions for the teacher in a responsive table.
 * 2. Marks all visible submissions as "seen" to clear dashboard notifications.
 * 3. Adapts for 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');

// --- Fetch all submissions and data for sidebar ---
try {
    // Fetch submission data for display
    $sql = "
        SELECT 
            sub.id as submission_id,
            sub.submitted_at,
            sub.grade,
            sub.graded_at,
            s.full_name as student_name,
            a.title as assignment_title,
            sub.file_path as submission_file,
            sub.parent_guardian_remark
        FROM submissions sub
        JOIN students s ON sub.student_id = s.id
        JOIN assignments a ON sub.assignment_id = a.id
        WHERE a.teacher_id = ?
        ORDER BY sub.submitted_at DESC
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$teacher_id]);
    $submissions = $stmt->fetchAll();

    // Mark these submissions as "seen" to clear notifications
    if (!empty($submissions)) {
        $submission_ids = array_column($submissions, 'submission_id');
        
        // Using IGNORE prevents errors if the teacher re-visits the page.
        $placeholders = rtrim(str_repeat('(?, ?),', count($submission_ids)), ',');
        $sql_mark_seen = "INSERT IGNORE INTO teacher_seen_submissions (teacher_id, submission_id) VALUES $placeholders";
        
        $params = [];
        foreach ($submission_ids as $sid) {
            $params[] = $teacher_id;
            $params[] = $sid;
        }

        $seen_stmt = $pdo->prepare($sql_mark_seen);
        $seen_stmt->execute($params);
    }
    
    // Fetch counts for sidebar badges
    $unread_messages_count = $pdo->query("SELECT COUNT(id) FROM teacher_messages WHERE teacher_id = {$teacher_id} AND is_read = 0 AND sender_type = 'admin'")->fetchColumn();
    // After marking as seen, the new submission count for the badge will be 0
    $new_submission_count = 0;


} catch (PDOException $e) {
    $submissions = [];
    $unread_messages_count = 0;
    $new_submission_count = 0;
    $page_error = "Could not fetch student submissions. " . $e->getMessage();
    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>View Submissions - 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; transition: background-color 0.2s, color 0.2s; 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; }

        /* Styles for Responsive Table */
        @media (max-width: 768px) {
            .responsive-table thead { display: none; }
            .responsive-table tr {
                display: block;
                margin-bottom: 1rem;
                border: 1px solid #ddd;
                border-radius: 0.5rem;
                padding: 1rem;
                box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            }
            .responsive-table td {
                display: flex;
                justify-content: space-between;
                align-items: center;
                text-align: right;
                padding: 0.5rem 0;
                border-bottom: 1px solid #eee;
            }
            .responsive-table td:last-child {
                border-bottom: none;
                flex-direction: column;
                align-items: stretch;
                padding-top: 1rem;
            }
             .responsive-table td:last-child a {
                margin: 0.25rem 0;
                text-align: center;
                padding: 0.5rem;
                border-radius: 0.375rem;
                border: 1px solid #ddd;
            }
            .responsive-table td::before {
                content: attr(data-label);
                font-weight: 600;
                text-align: left;
                padding-right: 1rem;
            }
        }
    </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 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 active 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">Student Submissions</h2>
                
                <?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-8 bg-white shadow-lg rounded-lg overflow-hidden">
                    <div class="overflow-x-auto">
                        <table class="min-w-full divide-y divide-gray-200 responsive-table">
                            <thead class="bg-gray-50">
                                <tr>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Student</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Assignment</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Submitted</th>
                                    <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Grade</th>
                                    <th class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                <?php if (empty($submissions)): ?>
                                    <tr><td colspan="5" class="text-center p-6 text-gray-500">No submissions found yet.</td></tr>
                                <?php else: ?>
                                    <?php foreach ($submissions as $sub): ?>
                                    <tr>
                                        <td data-label="Student" class="px-6 py-4 text-sm font-medium text-gray-900"><?php echo e($sub['student_name']); ?></td>
                                        <td data-label="Assignment" class="px-6 py-4 text-sm text-gray-500">
                                            <?php echo e($sub['assignment_title']); ?>
                                            <?php if(!empty($sub['parent_guardian_remark'])): ?>
                                                <span title="Parent's Remark: <?php echo e($sub['parent_guardian_remark']); ?>" class="ml-2 text-blue-500 cursor-pointer">&#128172;</span>
                                            <?php endif; ?>
                                        </td>
                                        <td data-label="Submitted" class="px-6 py-4 text-sm text-gray-500"><?php echo date('M d, Y', strtotime($sub['submitted_at'])); ?></td>
                                        <td data-label="Grade" class="px-6 py-4 text-sm font-semibold">
                                            <?php if (!empty($sub['grade'])): ?>
                                                <span><?php echo e($sub['grade']); ?></span>
                                                <span class="block text-xs text-gray-400">
                                                    <?php if (!empty($sub['graded_at'])) { echo date('M d, Y', strtotime($sub['graded_at'])); } ?>
                                                </span>
                                            <?php else: ?>
                                                <span class="text-gray-400">Pending</span>
                                            <?php endif; ?>
                                        </td>
                                        <td data-label="Actions" class="px-6 py-4 whitespace-nowrap text-sm font-medium text-center space-x-2">
                                            <a href="../<?php echo e($sub['submission_file']); ?>" download class="text-blue-600 hover:text-blue-900">Download</a>
                                            <a href="grade_submission.php?id=<?php echo e($sub['submission_id']); ?>" class="text-indigo-600 hover:text-indigo-900">
                                                <?php echo !empty($sub['grade']) ? 'Edit Grade' : 'Grade'; ?>
                                            </a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </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>
