<?php
/**
 * ===================================================================================
 * Post Material Page (Mobile Responsive)
 * ===================================================================================
 *
 * File: post_material.php
 * Location: /homework_portal/teacher/post_material.php
 *
 * Purpose:
 * 1. Allows teachers to upload assignments, notes, etc., via a responsive form.
 * 2. All submitted materials are automatically saved with a 'draft' status.
 * 3. Adapts for mobile, tablet, and desktop screens.
 */

require_once '../config.php';

// --- Security Check & Initial Setup ---
if (!isset($_SESSION['teacher_id'])) {
    header('Location: login.php');
    exit();
}
$teacher_id = $_SESSION['teacher_id'];
$teacher_full_name = e($_SESSION['teacher_full_name'] ?? 'Teacher');
$errors = [];
$success_message = '';

// --- Fetch data for dropdowns and sidebar badges ---
try {
    // Fetch teacher's assigned classes and subjects
    $sql = "SELECT DISTINCT c.id as class_id, c.class_name, s.id as subject_id, s.subject_name FROM teacher_subject_class tsc JOIN classes c ON tsc.class_id = c.id JOIN subjects s ON tsc.subject_id = s.id WHERE tsc.teacher_id = ? ORDER BY c.class_name, s.subject_name";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$teacher_id]);
    $teacher_assignments = $stmt->fetchAll();
    
    // 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();
    $new_submission_count = $pdo->query("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 = {$teacher_id} WHERE a.teacher_id = {$teacher_id} AND tss.submission_id IS NULL")->fetchColumn();

} catch (PDOException $e) {
    $teacher_assignments = [];
    $unread_messages_count = 0;
    $new_submission_count = 0;
    $errors[] = "Could not fetch your assigned classes and subjects.";
    error_log($e->getMessage());
}

// --- Handle Form Submission ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['post_material'])) {
    $status = 'draft'; 

    $class_subject = explode('_', $_POST['class_subject'] ?? '');
    $class_id = (int)($class_subject[0] ?? 0);
    $subject_id = (int)($class_subject[1] ?? 0);

    $title = trim($_POST['title'] ?? '');
    $post_type = trim($_POST['post_type'] ?? '');
    $instructions = trim($_POST['instructions'] ?? '');
    $due_date = !empty($_POST['due_date']) ? trim($_POST['due_date']) : null;
    
    $file_path_for_db = null;
    $file_type = null;

    if (isset($_FILES['assignment_file']) && $_FILES['assignment_file']['error'] == UPLOAD_ERR_OK) {
        $upload_dir_physical = __DIR__ . '/../uploads/assignments/';
        if (!is_dir($upload_dir_physical)) {
            mkdir($upload_dir_physical, 0755, true);
        }
        
        $file_name = uniqid() . '_' . basename($_FILES['assignment_file']['name']);
        $target_file_physical = $upload_dir_physical . $file_name;
        
        $file_path_for_db = 'uploads/assignments/' . $file_name;
        $file_type = $_FILES['assignment_file']['type'];

        if (!move_uploaded_file($_FILES['assignment_file']['tmp_name'], $target_file_physical)) {
            $errors[] = "There was an error uploading your file.";
            $file_path_for_db = null; 
        }
    }
    
    if (empty($class_id) || empty($subject_id)) $errors[] = "You must select a class and subject.";
    if (empty($title)) $errors[] = "Title is required.";

    if (empty($errors)) {
        $sql = "INSERT INTO assignments (teacher_id, class_id, subject_id, title, instructions, file_path, file_type, post_type, status, due_date) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try {
            $pdo->prepare($sql)->execute([$teacher_id, $class_id, $subject_id, $title, $instructions, $file_path_for_db, $file_type, $post_type, $status, $due_date]);
            $success_message = "Material saved successfully as a draft! You can publish it from the 'My Posted Materials' page.";
        } catch (PDOException $e) {
            $errors[] = "Database error: Could not save material.";
            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>Post Material - 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; }
    </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 active"><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">
                 <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6">
                    <h2 class="text-3xl font-semibold text-gray-800">Post New Material</h2>
                    <a href="dashboard.php" class="mt-2 sm:mt-0 flex items-center text-teal-600 hover:text-teal-800 font-medium">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"></path></svg>
                        Back to Dashboard
                    </a>
                </div>

                <!-- Feedback Messages -->
                <?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 (!empty($errors)): ?><div class="p-4 my-4 text-sm text-red-800 bg-red-100 rounded-lg"><ul class="list-disc list-inside"><?php foreach ($errors as $error) echo "<li>" . e($error) . "</li>"; ?></ul></div><?php endif; ?>

                <div class="mt-6 bg-white p-6 rounded-lg shadow">
                    <form action="post_material.php" method="POST" enctype="multipart/form-data" class="space-y-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label for="class_subject" class="block text-sm font-medium text-gray-700">Post to (Class - Subject)</label>
                                <select name="class_subject" id="class_subject" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                                    <option value="">Select a class and subject</option>
                                    <?php foreach($teacher_assignments as $assignment): ?>
                                        <option value="<?php echo e($assignment['class_id']); ?>_<?php echo e($assignment['subject_id']); ?>"><?php echo e($assignment['class_name']); ?> - <?php echo e($assignment['subject_name']); ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div>
                                <label for="post_type" class="block text-sm font-medium text-gray-700">Type of Material</label>
                                <select name="post_type" id="post_type" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                                    <option value="homework">Homework</option>
                                    <option value="notes">Notes</option>
                                    <option value="exam">Exam</option>
                                    <option value="announcement">Announcement</option>
                                    <option value="report">Performance Report</option>
                                </select>
                            </div>
                        </div>
                        <div>
                            <label for="title" class="block text-sm font-medium text-gray-700">Title / Headline</label>
                            <input type="text" name="title" id="title" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" required>
                        </div>
                        <div>
                            <label for="instructions" class="block text-sm font-medium text-gray-700">Instructions / Description</label>
                            <textarea name="instructions" id="instructions" rows="5" class="mt-1 block w-full p-2 border border-gray-300 rounded-md"></textarea>
                        </div>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label for="assignment_file" class="block text-sm font-medium text-gray-700">Attach File (Optional)</label>
                                <input type="file" name="assignment_file" id="assignment_file" class="mt-1 block w-full text-sm text-gray-500 file:mr-4 file:py-2 file:px-4 file:rounded-full file:border-0 file:text-sm file:font-semibold file:bg-blue-50 file:text-blue-700 hover:file:bg-blue-100">
                            </div>
                            <div>
                                <label for="due_date" class="block text-sm font-medium text-gray-700">Due Date (for Homework/Exams)</label>
                                <input type="datetime-local" name="due_date" id="due_date" class="mt-1 block w-full p-2 border border-gray-300 rounded-md">
                            </div>
                        </div>
                        <div class="text-right border-t pt-6">
                            <button type="submit" name="post_material" class="w-full sm:w-auto px-8 py-3 bg-teal-600 text-white font-bold rounded-lg shadow hover:bg-teal-700">Save as Draft</button>
                        </div>
                    </form>
                </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>
