<?php
// 1. Clean Environment & Error Suppression
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
ini_set('display_errors', 0);

session_start();
require_once 'config.php';

// Role Constants
if (!defined('ROLE_SUPER_ADMIN')) define('ROLE_SUPER_ADMIN', 1);
if (!defined('ROLE_ADMIN')) define('ROLE_ADMIN', 2);
if (!defined('ROLE_TEACHER')) define('ROLE_TEACHER', 3);
if (!defined('ROLE_STUDENT')) define('ROLE_STUDENT', 4);
if (!defined('ROLE_PARENT')) define('ROLE_PARENT', 5);
if (!defined('ROLE_STAFF')) define('ROLE_STAFF', 6);

// CSRF Token Generation
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// --- Helper Functions ---
function validatePDFFile($file_path) {
    $handle = fopen($file_path, 'rb');
    if (!$handle) return false;
    $header = fread($handle, 4);
    fclose($handle);
    return strpos($header, '%PDF') === 0;
}

function sanitizeFilePath($path) {
    return str_replace(['../', '..\\'], '', $path);
}

// --- Language Handling ---
$available_languages = ['en', 'lug', 'sw'];
$default_language = 'en';
if (isset($_GET['lang']) && in_array($_GET['lang'], $available_languages)) {
    $_SESSION['lang'] = $_GET['lang'];
} elseif (!isset($_SESSION['lang'])) {
    $_SESSION['lang'] = $default_language;
}
$current_lang = $_SESSION['lang'];

function load_language_data($lang) {
    $data = [
        'en' => [
            'sidebar_dashboard' => 'Dashboard',
            'sidebar_my_classes' => 'My Classes',
            'sidebar_my_students' => 'Students',
            'sidebar_assignments' => 'Assignments',
            'sidebar_grades' => 'Grades',
            'sidebar_messages' => 'Messages',
            'sidebar_calendar' => 'Calendar',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Logout',
            'page_title' => 'Assignments',
            'create_new' => 'Create New Assignment',
            'edit_assignment' => 'Edit Assignment',
            'recent_assignments' => 'Recent Assignments',
            'student_submissions' => 'Student Submissions',
            'no_assignments' => 'No assignments created yet.',
            'no_submissions' => 'No submissions received yet.',
            'more_menu' => 'More',
            'title_label' => 'Title',
            'desc_label' => 'Instructions',
            'subject_label' => 'Subject',
            'stream_label' => 'Class / Stream',
            'date_label' => 'Due Date',
            'file_label' => 'Attachment (PDF)',
            'btn_create' => 'Post Assignment',
            'btn_update' => 'Update Assignment',
            'success_create' => 'Assignment created successfully!',
            'success_update' => 'Assignment updated successfully!',
            'success_delete' => 'Assignment deleted successfully!',
            'error_general' => 'An error occurred.',
            'no_subjects_found' => 'No subjects found.',
            'no_class_streams_found' => 'No classes found.',
        ]
    ];
    return $data[$lang] ?? $data['en'];
}
$_L = load_language_data($current_lang);

// Auth Check
function check_role_access($required_role_code) {
    if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true || !isset($_SESSION["school_id"])) {
        header("location: login.php"); exit;
    }
    if ($_SESSION["role"] !== $required_role_code) {
        header("location: login.php"); exit;
    }
}
check_role_access(ROLE_TEACHER);

$currentPage = 'assignments';
$user_id = $_SESSION["id"];
$school_id = $_SESSION["school_id"];
$username = htmlspecialchars($_SESSION["username"] ?? '');
$role_name = "Teacher";

// Init Variables
$school_name = "Divine Reports";
$school_logo_path = "images/default_school_logo.png";
$teacher_photo = "images/default.png";
$subjects = [];
$streams = [];
$assignments = [];
$submissions = [];
$success_message = '';
$error_message = '';

// Edit Mode Logic
$edit_assignment_id = isset($_GET['edit_id']) ? intval($_GET['edit_id']) : 0;
$assignment_data = [];

// Handle Flash Messages
if (isset($_SESSION['flash_msg'])) {
    if ($_SESSION['flash_type'] == 'success') $success_message = $_SESSION['flash_msg'];
    else $error_message = $_SESSION['flash_msg'];
    unset($_SESSION['flash_msg'], $_SESSION['flash_type']);
}

if (isset($conn) && $conn instanceof mysqli) {
    
    // 1. Fetch Teacher Info
    $stmt = $conn->prepare("SELECT u.photo, s.school_name, s.logo FROM users u JOIN schools s ON u.school_id = s.school_id WHERE u.id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    if($row = $res->fetch_assoc()) {
        $teacher_photo = !empty($row['photo']) ? htmlspecialchars($row['photo']) : 'https://ui-avatars.com/api/?name='.urlencode($username).'&background=0a66c2&color=fff&size=128';
        $school_name = htmlspecialchars($row['school_name'] ?? '');
        $school_logo_path = !empty($row['logo']) ? htmlspecialchars($row['logo']) : 'images/default_school_logo.png';
    }
    $stmt->close();

    // 2. Fetch Dropdowns
    $stmt = $conn->prepare("SELECT subject_id, subject_name FROM subjects WHERE school_id = ?");
    $stmt->bind_param("i", $school_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while($row = $res->fetch_assoc()) $subjects[] = $row;
    $stmt->close();

    $stmt = $conn->prepare("SELECT stream_id, stream_name FROM streams WHERE school_id = ?");
    $stmt->bind_param("i", $school_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while($row = $res->fetch_assoc()) $streams[] = $row;
    $stmt->close();

    // 3. Handle DELETE
    if (isset($_GET['delete_id'])) {
        $del_id = intval($_GET['delete_id']);
        $stmt = $conn->prepare("SELECT file_path FROM assignments WHERE assignment_id = ? AND teacher_user_id = ?");
        $stmt->bind_param("ii", $del_id, $user_id);
        $stmt->execute();
        $stmt->bind_result($del_file_path);
        $stmt->fetch();
        $stmt->close();

        $stmt = $conn->prepare("DELETE FROM assignments WHERE assignment_id = ? AND teacher_user_id = ?");
        $stmt->bind_param("ii", $del_id, $user_id);
        if ($stmt->execute()) {
            if ($del_file_path && file_exists($del_file_path)) unlink($del_file_path);
            $_SESSION['flash_msg'] = $_L['success_delete'];
            $_SESSION['flash_type'] = 'success';
        } else {
            $_SESSION['flash_msg'] = $_L['error_general'];
            $_SESSION['flash_type'] = 'error';
        }
        header("Location: create_assignment.php");
        exit;
    }

    // 4. Handle POST (Create/Update)
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
            $error_message = "Invalid Security Token";
        } else {
            $aid = isset($_POST['assignment_id']) ? intval($_POST['assignment_id']) : 0;
            $title = trim($_POST['title']);
            $desc = trim($_POST['description']);
            $due = trim($_POST['due_date']);
            $sub_id = $_POST['subject_id'];
            $str_id = $_POST['stream_id'];
            $current_file = $_POST['current_file_path'] ?? null;
            
            if(empty($title) || empty($due) || empty($sub_id) || empty($str_id)) {
                $error_message = "Please fill in all required fields.";
            } else {
                $final_path = $current_file;
                if (isset($_FILES['assignment_file']) && $_FILES['assignment_file']['error'] === UPLOAD_ERR_OK) {
                    $f = $_FILES['assignment_file'];
                    $ext = strtolower(pathinfo($f['name'], PATHINFO_EXTENSION));
                    if ($ext === 'pdf' && $f['size'] <= 2*1024*1024) {
                        $upload_dir = 'uploads/assignments/';
                        if (!is_dir($upload_dir)) mkdir($upload_dir, 0755, true);
                        $new_name = uniqid('assign_', true) . '.pdf';
                        $dest = $upload_dir . $new_name;
                        if(move_uploaded_file($f['tmp_name'], $dest)) {
                            if(validatePDFFile($dest)) {
                                $final_path = $dest;
                                if($current_file && file_exists($current_file)) unlink($current_file);
                            } else {
                                unlink($dest);
                                $error_message = "Invalid PDF file.";
                            }
                        }
                    } else {
                        $error_message = "Invalid file. PDF only, max 2MB.";
                    }
                }

                if(empty($error_message)) {
                    if($aid == 0) { // INSERT
                        $stmt = $conn->prepare("INSERT INTO assignments (school_id, teacher_user_id, subject_id, stream_id, title, description, due_date, file_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        $stmt->bind_param("iiiissss", $school_id, $user_id, $sub_id, $str_id, $title, $desc, $due, $final_path);
                        if($stmt->execute()) {
                            $_SESSION['flash_msg'] = $_L['success_create'];
                            $_SESSION['flash_type'] = 'success';
                            header("Location: create_assignment.php");
                            exit;
                        } else {
                            $error_message = "Database Error: " . $stmt->error;
                        }
                    } else { // UPDATE
                        $stmt = $conn->prepare("UPDATE assignments SET subject_id=?, stream_id=?, title=?, description=?, due_date=?, file_path=? WHERE assignment_id=? AND teacher_user_id=?");
                        $stmt->bind_param("iissssii", $sub_id, $str_id, $title, $desc, $due, $final_path, $aid, $user_id);
                        if($stmt->execute()) {
                            $_SESSION['flash_msg'] = $_L['success_update'];
                            $_SESSION['flash_type'] = 'success';
                            header("Location: create_assignment.php?edit_id=" . $aid);
                            exit;
                        } else {
                            $error_message = "Database Error: " . $stmt->error;
                        }
                    }
                }
            }
        }
    }

    // 5. Fetch Data for Edit Mode
    if ($edit_assignment_id > 0) {
        $stmt = $conn->prepare("SELECT * FROM assignments WHERE assignment_id = ? AND teacher_user_id = ?");
        $stmt->bind_param("ii", $edit_assignment_id, $user_id);
        $stmt->execute();
        $res = $stmt->get_result();
        $assignment_data = $res->fetch_assoc() ?: [];
        $stmt->close();
    }

    // 6. Fetch Recent Assignments Feed (LIMITED TO 5)
    $stmt = $conn->prepare("SELECT a.*, s.subject_name, st.stream_name 
                            FROM assignments a 
                            JOIN subjects s ON a.subject_id = s.subject_id 
                            JOIN streams st ON a.stream_id = st.stream_id 
                            WHERE a.teacher_user_id = ? 
                            ORDER BY a.created_at DESC LIMIT 5");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $res = $stmt->get_result();
    while($row = $res->fetch_assoc()) $assignments[] = $row;
    $stmt->close();

    // 7. Fetch Submissions
    if ($edit_assignment_id > 0) {
        $stmt = $conn->prepare("SELECT sub.*, u.username, u.photo FROM assignment_submissions sub JOIN users u ON sub.student_id = u.id WHERE sub.assignment_id = ? ORDER BY sub.submitted_at DESC");
        $stmt->bind_param("i", $edit_assignment_id);
    } else {
        $stmt = $conn->prepare("SELECT sub.*, u.username, u.photo, a.title as assignment_title FROM assignment_submissions sub JOIN users u ON sub.student_id = u.id JOIN assignments a ON sub.assignment_id = a.assignment_id WHERE a.teacher_user_id = ? ORDER BY sub.submitted_at DESC LIMIT 5");
        $stmt->bind_param("i", $user_id);
    }
    $stmt->execute();
    $res = $stmt->get_result();
    while($row = $res->fetch_assoc()) {
        $row['photo'] = $row['photo'] ?: 'https://ui-avatars.com/api/?name='.urlencode($row['username']).'&background=0a66c2&color=fff';
        $submissions[] = $row;
    }
    $stmt->close();
    
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#0a66c2">
    <title><?php echo $_L['page_title']; ?> | <?php echo $school_name; ?></title>
    
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">

    <style>
        body { font-family: 'Inter', sans-serif; background-color: #f3f2ef; color: #191919; }
        .sidebar-desktop { background-color: #ffffff; border-right: 1px solid #e0dfdc; }
        .sidebar-link { display: flex; align-items: center; padding: 12px 24px; color: #666666; font-weight: 600; border-left: 4px solid transparent; transition: all 0.2s; }
        .sidebar-link:hover { background-color: #f3f2ef; color: #191919; }
        .sidebar-link.active { border-left-color: #0a66c2; background-color: white; color: #0a66c2; }
        .form-input { width: 100%; padding: 10px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 0.95rem; transition: all 0.2s; }
        .form-input:focus { border-color: #0a66c2; outline: none; box-shadow: 0 0 0 3px rgba(10, 102, 194, 0.1); }
        .card { background: white; border-radius: 8px; border: 1px solid #e0dfdc; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .feed-item { padding: 16px; border-bottom: 1px solid #f3f2ef; transition: background 0.2s; }
        .feed-item:hover { background-color: #f9fafb; }
        .feed-item:last-child { border-bottom: none; }
        .nav-item { color: #666; transition: color 0.2s; }
        .nav-item.active { color: #0a66c2; }
        .nav-item.active i { transform: translateY(-2px); }
        @media (min-width: 1024px) { .mobile-only { display: none !important; } .sidebar-desktop { display: flex !important; } .main-content { margin-left: 260px; } }
        @media (max-width: 1023px) { .desktop-only { display: none !important; } .sidebar-desktop { display: none !important; } .main-content { margin-left: 0; padding-bottom: 80px; } }
    </style>
</head>
<body class="antialiased">

    <aside class="sidebar-desktop fixed top-0 left-0 h-full z-50 flex-col w-[260px] hidden lg:flex">
        <div class="h-16 flex items-center px-6 border-b border-gray-200 bg-white">
            <img src="<?php echo $school_logo_path; ?>" alt="Logo" class="h-8 w-8 object-contain mr-2">
            <h1 class="font-bold text-[#0a66c2] text-sm">DIVINE REPORTS</h1>
        </div>
        <nav class="flex-1 overflow-y-auto py-4">
            <a href="teacher_dashboard.php" class="sidebar-link"><i class="fas fa-th-large w-6"></i> <?php echo $_L['sidebar_dashboard']; ?></a>
            <a href="teacher_my_classes.php" class="sidebar-link"><i class="fas fa-chalkboard w-6"></i> <?php echo $_L['sidebar_my_classes']; ?></a>
            <a href="teacher_my_students.php" class="sidebar-link"><i class="fas fa-user-graduate w-6"></i> <?php echo $_L['sidebar_my_students']; ?></a>
            <a href="create_assignment.php" class="sidebar-link active"><i class="fas fa-file-alt w-6"></i> <?php echo $_L['sidebar_assignments']; ?></a>
            <a href="teacher_exams.php" class="sidebar-link"><i class="fas fa-award w-6"></i> <?php echo $_L['sidebar_grades']; ?></a>
            <a href="teacher_messages.php" class="sidebar-link"><i class="fas fa-envelope w-6"></i> <?php echo $_L['sidebar_messages']; ?></a>
            <a href="teacher_calendar.php" class="sidebar-link"><i class="far fa-calendar-alt w-6"></i> <?php echo $_L['sidebar_calendar']; ?></a>
        </nav>
        <div class="p-4 border-t border-gray-200"><a href="logout.php" class="flex items-center px-4 py-2 text-gray-500 hover:text-red-600 font-semibold"><i class="fas fa-sign-out-alt mr-3"></i> Logout</a></div>
    </aside>

    <header class="mobile-only fixed top-0 w-full bg-white z-40 px-4 py-3 border-b border-gray-200 flex justify-between items-center shadow-sm">
        <div class="flex items-center gap-2">
            <img src="<?php echo $school_logo_path; ?>" class="h-8 w-8 object-contain rounded">
            <h1 class="font-bold text-[#0a66c2] text-sm truncate max-w-[150px]"><?php echo htmlspecialchars($school_name); ?></h1>
        </div>
        <img src="<?php echo $teacher_photo; ?>" class="h-8 w-8 rounded-full border border-gray-300 object-cover">
    </header>

    <header class="desktop-only fixed top-0 right-0 left-[260px] bg-white h-16 z-40 px-8 flex justify-between items-center border-b border-gray-200">
        <h2 class="text-lg font-bold text-gray-800"><?php echo $_L['page_title']; ?></h2>
        <div class="flex items-center gap-4">
            <div class="text-right">
                <p class="text-sm font-semibold text-gray-900"><?php echo $username; ?></p>
                <p class="text-xs text-gray-500">Teacher</p>
            </div>
            <img src="<?php echo $teacher_photo; ?>" class="h-9 w-9 rounded-full border border-gray-200 object-cover">
        </div>
    </header>

    <main class="main-content pt-20 lg:pt-24 px-4 lg:px-8 pb-10 min-h-screen">
        
        <?php if($success_message): ?>
            <div class="bg-green-100 border border-green-200 text-green-800 px-4 py-3 rounded-lg mb-6 flex items-center shadow-sm">
                <i class="fas fa-check-circle mr-2"></i> <?php echo $success_message; ?>
            </div>
        <?php endif; ?>
        <?php if($error_message): ?>
            <div class="bg-red-100 border border-red-200 text-red-800 px-4 py-3 rounded-lg mb-6 flex items-center shadow-sm">
                <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error_message; ?>
            </div>
        <?php endif; ?>

        <div class="flex flex-col lg:flex-row gap-6">
            
            <div class="w-full lg:w-2/3">
                <div class="card p-6 mb-6">
                    <div class="flex justify-between items-center mb-6">
                        <h3 class="text-xl font-bold text-gray-900">
                            <?php echo ($edit_assignment_id > 0) ? $_L['edit_assignment'] : $_L['create_new']; ?>
                        </h3>
                        <?php if($edit_assignment_id > 0): ?>
                            <a href="create_assignment.php" class="text-sm text-[#0a66c2] font-semibold hover:underline">Cancel Edit</a>
                        <?php endif; ?>
                    </div>

                    <form action="" method="POST" enctype="multipart/form-data" class="space-y-6">
                        <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
                        <?php if($edit_assignment_id > 0): ?>
                            <input type="hidden" name="assignment_id" value="<?php echo $edit_assignment_id; ?>">
                            <input type="hidden" name="current_file_path" value="<?php echo htmlspecialchars($assignment_data['file_path'] ?? ''); ?>">
                        <?php endif; ?>
                        
                        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                            <div class="col-span-1 lg:col-span-2">
                                <label class="block text-sm font-semibold text-gray-700 mb-1"><?php echo $_L['title_label']; ?></label>
                                <input type="text" name="title" class="form-input" placeholder="e.g. Algebra Homework #4" value="<?php echo htmlspecialchars($assignment_data['title'] ?? ''); ?>" required>
                            </div>

                            <div class="col-span-1 lg:col-span-2">
                                <label class="block text-sm font-semibold text-gray-700 mb-1"><?php echo $_L['subject_label']; ?></label>
                                <select name="subject_id" class="form-input bg-white" required>
                                    <option value="">Select Subject</option>
                                    <?php if(empty($subjects)): ?>
                                        <option disabled><?php echo $_L['no_subjects_found'] ?? 'No Subjects'; ?></option>
                                    <?php else: ?>
                                        <?php foreach($subjects as $s): ?>
                                            <option value="<?php echo $s['subject_id']; ?>" <?php echo (isset($assignment_data['subject_id']) && $assignment_data['subject_id'] == $s['subject_id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($s['subject_name'] ?? ''); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                            </div>

                            <div class="col-span-1 lg:col-span-2">
                                <label class="block text-sm font-semibold text-gray-700 mb-1"><?php echo $_L['stream_label']; ?></label>
                                <select name="stream_id" class="form-input bg-white" required>
                                    <option value="">Select Class</option>
                                    <?php if(empty($streams)): ?>
                                        <option disabled><?php echo $_L['no_class_streams_found'] ?? 'No Classes'; ?></option>
                                    <?php else: ?>
                                        <?php foreach($streams as $s): ?>
                                            <option value="<?php echo $s['stream_id']; ?>" <?php echo (isset($assignment_data['stream_id']) && $assignment_data['stream_id'] == $s['stream_id']) ? 'selected' : ''; ?>>
                                                <?php echo htmlspecialchars($s['stream_name'] ?? ''); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    <?php endif; ?>
                                </select>
                            </div>

                            <div class="col-span-1">
                                <label class="block text-sm font-semibold text-gray-700 mb-1"><?php echo $_L['date_label']; ?></label>
                                <input type="date" name="due_date" class="form-input" value="<?php echo htmlspecialchars($assignment_data['due_date'] ?? ''); ?>" required>
                            </div>

                            <div class="col-span-1">
                                <label class="block text-sm font-semibold text-gray-700 mb-1"><?php echo $_L['file_label']; ?></label>
                                <input type="file" name="assignment_file" accept=".pdf" class="form-input text-sm text-gray-500 file:mr-4 file:py-1 file:px-3 file:rounded-full file:border-0 file:text-xs file:font-semibold file:bg-blue-50 file:text-[#0a66c2] hover:file:bg-blue-100">
                                <?php if(!empty($assignment_data['file_path']) && file_exists($assignment_data['file_path'])): ?>
                                    <div class="mt-2 text-xs text-green-600 flex items-center font-bold">
                                        <i class="fas fa-check-circle mr-1"></i> Current file active
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div class="col-span-1 lg:col-span-2">
                                <label class="block text-sm font-semibold text-gray-700 mb-1"><?php echo $_L['desc_label']; ?></label>
                                <textarea name="description" rows="4" class="form-input" placeholder="Detailed instructions..."><?php echo htmlspecialchars($assignment_data['description'] ?? ''); ?></textarea>
                            </div>
                        </div>

                        <div class="pt-4 flex justify-end">
                            <button type="submit" class="bg-[#0a66c2] hover:bg-[#004182] text-white px-6 py-2.5 rounded-full font-bold text-sm shadow-sm transition-all">
                                <?php echo ($edit_assignment_id > 0) ? $_L['btn_update'] : $_L['btn_create']; ?>
                            </button>
                        </div>
                    </form>
                </div>

                <div class="card p-6">
                    <h3 class="text-lg font-bold text-gray-900 mb-4"><?php echo $_L['student_submissions']; ?></h3>
                    <?php if (empty($submissions)): ?>
                        <div class="text-center py-8 text-gray-500">
                            <i class="fas fa-folder-open text-3xl mb-2 text-gray-300"></i>
                            <p class="text-sm"><?php echo $_L['no_submissions']; ?></p>
                        </div>
                    <?php else: ?>
                        <div class="space-y-3">
                            <?php foreach($submissions as $sub): ?>
                            <div class="flex items-center justify-between p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition">
                                <div class="flex items-center gap-3">
                                    <img src="<?php echo $sub['photo']; ?>" class="w-10 h-10 rounded-full object-cover border border-gray-200">
                                    <div>
                                        <p class="text-sm font-bold text-gray-900"><?php echo htmlspecialchars($sub['username'] ?? ''); ?></p>
                                        <p class="text-xs text-gray-500"><?php echo ($edit_assignment_id == 0) ? 'For: '.htmlspecialchars($sub['assignment_title'] ?? '') : 'Submitted: '.date('M d, H:i', strtotime($sub['submitted_at'])); ?></p>
                                    </div>
                                </div>
                                <?php if(file_exists($sub['submission_path'] ?? '')): ?>
                                    <a href="<?php echo $sub['submission_path']; ?>" target="_blank" class="text-xs font-semibold text-[#0a66c2] bg-blue-50 px-3 py-1.5 rounded-full hover:bg-blue-100 transition">
                                        Download <i class="fas fa-download ml-1"></i>
                                    </a>
                                <?php else: ?>
                                    <span class="text-xs text-red-400 italic">File Missing</span>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <div class="w-full lg:w-1/3">
                <div class="card sticky top-24">
                    <div class="p-4 border-b border-gray-100 bg-gray-50 rounded-t-lg">
                        <h3 class="font-bold text-gray-800"><?php echo $_L['recent_assignments']; ?></h3>
                    </div>
                    
                    <div class="max-h-[600px] overflow-y-auto">
                        <?php if (empty($assignments)): ?>
                            <div class="p-6 text-center text-gray-500 text-sm"><?php echo $_L['no_assignments']; ?></div>
                        <?php else: ?>
                            <?php foreach ($assignments as $assign): ?>
                            <div class="feed-item group relative">
                                <div class="flex flex-wrap items-center gap-2 mb-2">
                                    <span class="text-[10px] font-bold text-[#0a66c2] bg-blue-50 px-2 py-0.5 rounded uppercase tracking-wide">
                                        <?php echo htmlspecialchars($assign['subject_name'] ?? ''); ?>
                                    </span>
                                    <span class="text-[10px] font-semibold text-gray-500 bg-gray-100 px-2 py-0.5 rounded">
                                        <?php echo htmlspecialchars($assign['stream_name'] ?? ''); ?>
                                    </span>
                                </div>
                                
                                <h4 class="text-sm font-bold text-gray-900 mb-1 leading-snug">
                                    <?php echo htmlspecialchars($assign['title'] ?? ''); ?>
                                </h4>
                                <p class="text-xs text-gray-500 mb-2 line-clamp-2">
                                    <?php echo htmlspecialchars($assign['description'] ?? ''); ?>
                                </p>
                                
                                <div class="flex items-center justify-between text-xs text-gray-400 mt-2">
                                    <span><i class="far fa-clock mr-1"></i> Due: <?php echo date('M d', strtotime($assign['due_date'])); ?></span>
                                    
                                    <div class="flex items-center gap-3">
                                        <?php 
                                        $db_path = htmlspecialchars($assign['file_path'] ?? '');
                                        if(!empty($db_path) && file_exists($db_path)): 
                                        ?>
                                            <a href="<?php echo $db_path; ?>" target="_blank" class="text-[#0a66c2] hover:underline flex items-center">
                                                <i class="fas fa-paperclip mr-1"></i> PDF
                                            </a>
                                        <?php endif; ?>
                                        
                                        <div class="flex gap-2">
                                            <a href="?edit_id=<?php echo $assign['assignment_id']; ?>" class="text-gray-400 hover:text-[#0a66c2]"><i class="fas fa-pen"></i></a>
                                            <a href="?delete_id=<?php echo $assign['assignment_id']; ?>" class="text-gray-400 hover:text-red-600" onclick="return confirm('Delete this assignment?');"><i class="fas fa-trash"></i></a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

        </div>
    </main>

    <nav class="mobile-only fixed bottom-0 left-0 w-full bg-white border-t border-gray-200 z-50 flex justify-around items-center h-[70px] pb-safe shadow-[0_-4px_10px_rgba(0,0,0,0.05)]">
        <a href="teacher_dashboard.php" class="nav-item flex flex-col items-center justify-center w-full h-full text-gray-500 hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-th-large text-xl mb-1"></i><span class="text-[10px] font-medium">Home</span>
        </a>
        <a href="create_assignment.php" class="nav-item active flex flex-col items-center justify-center w-full h-full text-[#0a66c2] font-bold transition-colors">
            <i class="fas fa-file-alt text-xl mb-1"></i><span class="text-[10px]">Work</span>
        </a>
        <a href="teacher_my_classes.php" class="nav-item flex flex-col items-center justify-center w-full h-full text-gray-500 hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-chalkboard text-xl mb-1"></i><span class="text-[10px] font-medium">Classes</span>
        </a>
        <button onclick="toggleMoreMenu(true)" class="nav-item flex flex-col items-center justify-center w-full h-full text-gray-500 hover:text-[#0a66c2] transition-colors">
            <i class="fas fa-ellipsis-h text-xl mb-1"></i><span class="text-[10px] font-medium">More</span>
        </button>
    </nav>

    <div id="moreMenuBackdrop" onclick="toggleMoreMenu(false)" class="fixed inset-0 bg-black/40 z-[60] hidden transition-opacity opacity-0"></div>
    <div id="moreMenu" class="mobile-only fixed bottom-0 left-0 w-full bg-white rounded-t-xl z-[70] transform translate-y-full transition-transform duration-300 ease-out shadow-2xl pb-safe">
        <div class="w-10 h-1 bg-gray-300 rounded-full mx-auto my-3"></div>
        <div class="grid grid-cols-3 gap-3 p-5">
            <a href="teacher_my_students.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-[#0a66c2] mb-1 text-xl"><i class="fas fa-user-graduate"></i></div><span class="text-[10px] font-bold text-gray-600">Students</span></a>
            <a href="teacher_exams.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-blue-600 mb-1 text-xl"><i class="fas fa-award"></i></div><span class="text-[10px] font-bold text-gray-600">Grades</span></a>
            <a href="teacher_messages.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-purple-600 mb-1 text-xl"><i class="fas fa-envelope"></i></div><span class="text-[10px] font-bold text-gray-600">Messages</span></a>
            <a href="teacher_calendar.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-teal-600 mb-1 text-xl"><i class="far fa-calendar-alt"></i></div><span class="text-[10px] font-bold text-gray-600">Calendar</span></a>
            <a href="teacher_settings.php" class="flex flex-col items-center p-3 hover:bg-gray-50 rounded-lg"><div class="text-gray-600 mb-1 text-xl"><i class="fas fa-cog"></i></div><span class="text-[10px] font-bold text-gray-600">Settings</span></a>
        </div>
        <div class="p-5 pt-0"><a href="logout.php" class="flex items-center justify-center w-full py-3 bg-gray-100 text-gray-700 rounded-lg font-bold"><i class="fas fa-sign-out-alt mr-2"></i> Logout</a></div>
    </div>

    <script>
        const moreMenuBackdrop = document.getElementById('moreMenuBackdrop');
        const moreMenu = document.getElementById('moreMenu');

        function toggleMoreMenu(show) {
            if(show) {
                moreMenuBackdrop.classList.remove('hidden');
                setTimeout(() => {
                    moreMenuBackdrop.classList.remove('opacity-0');
                    moreMenu.classList.remove('translate-y-full');
                }, 10);
            } else {
                moreMenuBackdrop.classList.add('opacity-0');
                moreMenu.classList.add('translate-y-full');
                setTimeout(() => { moreMenuBackdrop.classList.add('hidden'); }, 300);
            }
        }
    </script>
</body>
</html>