<?php
session_start(); // Start the session to access session variables

require_once 'config.php'; // Include the database configuration file. Ensure this path is correct.

// Define 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);

// --- Language Handling and Localization Dictionary ---
$available_languages = ['en', 'lug', 'sw']; // English, Luganda, Kiswahili
$default_language = 'en';

// Check if a language is selected via GET parameter; otherwise, use session or default.
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'];

/**
 * Loads language-specific strings.
 * @param string $lang The current language code.
 * @return array An associative array of localized strings.
 */
function load_language_data($lang) {
    $data = [
        'en' => [
            'dashboard_title_prefix' => 'Student Dashboard',
            'sidebar_dashboard' => 'Dashboard',
            'sidebar_profile' => 'Profile',
            'sidebar_reports' => 'Reports',
            'sidebar_assignments' => 'Assignments',
            'sidebar_messages' => 'Messages',
            'sidebar_settings' => 'Settings',
            'sidebar_logout' => 'Logout',
            'school_name_not_found' => 'School Name Not Found',
            'search_placeholder' => 'Search assignments',
            'welcome_message_prefix' => 'Welcome',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Logged in as:',
            'divine_reports' => 'DIVINE REPORTS',
            'assignments_heading' => 'My Assignments',
            'title_column' => 'Title',
            'subject_column' => 'Subject',
            'due_date_column' => 'Due Date',
            'description_column' => 'Description',
            'assigned_by_column' => 'Assigned By (Teacher)',
            'submission_column' => 'Submission',
            'upload_assignment' => 'Upload Assignment',
            'edit_submission' => 'Edit Submission',
            'select_file_label' => 'Select PDF File',
            'submit_button' => 'Submit',
            'countdown_prefix' => 'Due in',
            'countdown_past_due' => 'Past Due',
            'submitted_status' => 'Submitted',
            'upload_success' => 'Assignment submitted successfully!',
            'resubmit_success' => 'Assignment re-submitted successfully!',
            'upload_error' => 'Failed to submit assignment.',
            'file_type_error' => 'Only PDF files are allowed.',
            'file_size_error' => 'File size exceeds limit (max 5MB).',
            'no_file_selected' => 'Please select a file to upload.',
            'unsubmitted_status' => 'Unsubmitted',
            'uploading_message' => 'Uploading...',
            'already_submitted_past_due' => 'Submitted (Past Due)',
            'no_assignments_found' => 'No assignments found.' // FIXED: Added missing translation
        ],
        'lug' => [
            'dashboard_title_prefix' => 'Diisiboodi y\'Omuyizi',
            'sidebar_dashboard' => 'Diisiboodi',
            'sidebar_profile' => 'Purofayiro',
            'sidebar_reports' => 'Lipooti',
            'sidebar_assignments' => 'Ebitongole',
            'sidebar_messages' => 'Obubaka',
            'sidebar_settings' => 'Enteekateeka',
            'sidebar_logout' => 'Log Out',
            'school_name_not_found' => 'Erinnya ly\'Essomero Terinnaba Kulabika',
            'search_placeholder' => 'Noonya ebitongole',
            'welcome_message_prefix' => 'Mpulira Olamusiddwa',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Oyinze okukakasa nga:',
            'divine_reports' => 'RIPOTA ZA MUNGU',
            'assignments_heading' => 'Ebitongole Byange',
            'title_column' => 'Omutwe',
            'subject_column' => 'Eky\'okusomesebwa',
            'due_date_column' => 'Ennaku Zokukomya',
            'description_column' => 'Okunnyonnyola',
            'assigned_by_column' => 'Ekitongole ky\'Omusomesa',
            'submission_column' => 'Okuweereza',
            'upload_assignment' => 'Weereza Ekitongole',
            'edit_submission' => 'Ffula Ekitongole',
            'select_file_label' => 'Londa Fayiro ya PDF',
            'submit_button' => 'Weereza',
            'countdown_prefix' => 'Ekomya mu',
            'countdown_past_due' => 'Kyaweddeko',
            'submitted_status' => 'Kiwedde',
            'upload_success' => 'Ekitongole kiwedde bulungi!',
            'resubmit_success' => 'Ekitongole kiffuliddwa bulungi!',
            'upload_error' => 'Okuteekawo ekitongole kigaanye.',
            'file_type_error' => 'Fayiro za PDF zokka zemukkirizibwa.',
            'file_size_error' => 'Obunene bwa fayiro businze (max 5MB).',
            'no_file_selected' => 'Londa fayiro gy\'onooteekawo.',
            'unsubmitted_status' => 'Tetennateekebwa',
            'uploading_message' => 'Nteekawo...',
            'already_submitted_past_due' => 'Kiwedde (Kyaweddeko)',
            'no_assignments_found' => 'Tewali bitongole birabika.' // FIXED: Added missing translation
        ],
        'sw' => [
            'dashboard_title_prefix' => 'Dashibodi ya Mwanafunzi',
            'sidebar_dashboard' => 'Dashibodi',
            'sidebar_profile' => 'Wasifu',
            'sidebar_reports' => 'Ripoti',
            'sidebar_assignments' => 'Kazi',
            'sidebar_messages' => 'Ujumbe',
            'sidebar_settings' => 'Mipangilio',
            'sidebar_logout' => 'Ondoka',
            'school_name_not_found' => 'Jina la Shule Halikupatikana',
            'search_placeholder' => 'Tafuta kazi',
            'welcome_message_prefix' => 'Karibu',
            'welcome_message_suffix' => '!',
            'logged_in_as' => 'Umeingia kama:',
            'divine_reports' => 'RIPOTI ZA MUNGU',
            'assignments_heading' => 'Kazi Zangu',
            'title_column' => 'Kichwa',
            'subject_column' => 'Somo',
            'due_date_column' => 'Tarehe ya Mwisho',
            'description_column' => 'Maelezo',
            'assigned_by_column' => 'Imetolewa na (Mwalimu)',
            'submission_column' => 'Wasilisho',
            'upload_assignment' => 'Pakia Kazi',
            'edit_submission' => 'Hariri Wasilisho',
            'select_file_label' => 'Chagua Faili ya PDF',
            'submit_button' => 'Wasilisha',
            'countdown_prefix' => 'Muda uliosalia',
            'countdown_past_due' => 'Muda Umepita',
            'submitted_status' => 'Imewasilishwa',
            'upload_success' => 'Kazi imewasilishwa kwa mafanikio!',
            'resubmit_success' => 'Kazi imewasilishwa tena kwa mafanikio!',
            'upload_error' => 'Imeshindwa kuwasilisha kazi.',
            'file_type_error' => 'Faili za PDF pekee ndizo zinaruhusiwa.',
            'file_size_error' => 'Ukubwa wa faili umezidi kiwango (max 5MB).',
            'no_file_selected' => 'Tafadhali chagua faili ya kupakia.',
            'unsubmitted_status' => 'Haijawasilishwa',
            'uploading_message' => 'Inapakia...',
            'already_submitted_past_due' => 'Imewasilishwa (Muda Umepita)',
            'no_assignments_found' => 'Hakuna kazi zilizopatikana.' // FIXED: Added missing translation
        ]
    ];
    return $data[$lang] ?? $data['en']; // Fallback to English if language not found
}

$_L = load_language_data($current_lang);

/**
 * Function to check the user's role and redirect if they are unauthorized to access the current page.
 * @param int $required_role_code The role code required to access this page.
 */
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) {
        switch ($_SESSION["role"]) {
            case ROLE_SUPER_ADMIN:
                header("location: super_admin_dashboard.php");
                break;
            case ROLE_ADMIN:
                header("location: admin_dashboard.php");
                break;
            case ROLE_TEACHER:
                header("location: teacher_dashboard.php");
                break;
            default:
                header("location: login.php");
                break;
        }
        exit;
    }
}

check_role_access(ROLE_STUDENT);

$currentPage = 'assignments';

$student_user_id = $_SESSION["id"];
$school_id = $_SESSION["school_id"];
$username = htmlspecialchars($_SESSION["username"]);
$user_role_code = $_SESSION["role"];

$student_photo = "images/default_student_photo.png";
$school_name = $_L['school_name_not_found'];
$school_logo_path = "images/default_school_logo.png";

$role_name = "Unknown";
switch ($user_role_code) {
    case ROLE_SUPER_ADMIN: $role_name = "Super Admin"; break;
    case ROLE_ADMIN:        $role_name = "Admin";       break;
    case ROLE_TEACHER:      $role_name = "Teacher";     break;
    case ROLE_STUDENT:      $role_name = "Student";     break;
    case ROLE_PARENT:       $role_name = "Parent";      break;
    case ROLE_STAFF:        $role_name = "Staff";       break;
}

// --- CONCEPTUAL DATABASE TABLE FOR ASSIGNMENT SUBMISSIONS ---
// In a real application, you would run this SQL query to create the table
// if it doesn't already exist.
/*
CREATE TABLE `assignment_submissions` (
    `submission_id` INT AUTO_INCREMENT PRIMARY KEY,
    `assignment_id` INT NOT NULL,
    `student_id` INT NOT NULL,
    `submission_path` VARCHAR(255) NOT NULL,
    `submitted_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `is_resubmission` TINYINT(1) DEFAULT 0,
    UNIQUE KEY `uk_assignment_student` (`assignment_id`, `student_id`),
    FOREIGN KEY (`assignment_id`) REFERENCES `assignments`(`assignment_id`) ON DELETE CASCADE,
    FOREIGN KEY (`student_id`) REFERENCES `users`(`id`) ON DELETE CASCADE
);
*/
// --- END CONCEPTUAL DATABASE TABLE ---

// Handle assignment submission via AJAX
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] == 'submit_assignment') {
    header('Content-Type: application/json');
    ini_set('display_errors', 0);
    error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);

    if (!isset($conn) || !$conn instanceof mysqli) {
        require 'config.php';
        if (!isset($conn) || !$conn instanceof mysqli) {
            echo json_encode(['success' => false, 'message' => 'Database connection error for AJAX request.']);
            exit;
        }
    }

    $assignment_id = filter_input(INPUT_POST, 'assignment_id', FILTER_VALIDATE_INT);
    $response = ['success' => false, 'message' => $_L['upload_error']];

    if (!$assignment_id) {
        $response['message'] = 'Invalid assignment ID.';
        echo json_encode($response);
        $conn->close();
        exit;
    }

    // Fetch assignment due date to check if submission is still allowed
    $sql_get_due_date = "SELECT due_date FROM assignments WHERE assignment_id = ? AND school_id = ?";
    $due_date_obj = null;
    if ($stmt_due_date = $conn->prepare($sql_get_due_date)) {
        $stmt_due_date->bind_param("ii", $assignment_id, $school_id);
        if ($stmt_due_date->execute()) {
            $stmt_due_date->bind_result($due_date_str);
            if ($stmt_due_date->fetch()) {
                $due_date_obj = new DateTime($due_date_str);
            }
        }
        $stmt_due_date->close();
    }

    if ($due_date_obj === null) {
        $response['message'] = "Assignment not found or due date not available.";
        echo json_encode($response);
        $conn->close();
        exit;
    }

    $now = new DateTime();
    if ($now > $due_date_obj) {
        $response['message'] = "Cannot submit: Assignment is past due.";
        echo json_encode($response);
        $conn->close();
        exit;
    }

    if (isset($_FILES['assignment_file']) && $_FILES['assignment_file']['error'] === UPLOAD_ERR_OK) {
        $file_tmp_name = $_FILES['assignment_file']['tmp_name'];
        $file_name = $_FILES['assignment_file']['name'];
        $file_size = $_FILES['assignment_file']['size'];
        $file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

        $allowed_ext = ['pdf'];
        $max_file_size = 5 * 1024 * 1024; // 5 MB

        if (!in_array($file_ext, $allowed_ext)) {
            $response['message'] = $_L['file_type_error'];
        } elseif ($file_size > $max_file_size) {
            $response['message'] = $_L['file_size_error'];
        } else {
            $upload_dir = 'uploads/assignments/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }

            // Check if a previous submission exists for this assignment and student
            $existing_submission_path = null;
            $sql_check_submission = "SELECT submission_path FROM assignment_submissions WHERE assignment_id = ? AND student_id = ?";
            if ($stmt_check = $conn->prepare($sql_check_submission)) {
                $stmt_check->bind_param("ii", $assignment_id, $student_user_id);
                $stmt_check->execute();
                $stmt_check->bind_result($path_db);
                if ($stmt_check->fetch()) {
                    $existing_submission_path = $path_db;
                }
                $stmt_check->close();
            }

            $new_file_name = 'assignment_' . $assignment_id . '_student_' . $student_user_id . '_' . time() . '.' . $file_ext;
            $destination_path = $upload_dir . $new_file_name;

            if (move_uploaded_file($file_tmp_name, $destination_path)) {
                if ($existing_submission_path) {
                    // Update existing submission
                    $sql_update_submission = "UPDATE assignment_submissions SET submission_path = ?, submitted_at = NOW(), is_resubmission = 1 WHERE assignment_id = ? AND student_id = ?";
                    if ($stmt_update = $conn->prepare($sql_update_submission)) {
                        $stmt_update->bind_param("sii", $destination_path, $assignment_id, $student_user_id);
                        if ($stmt_update->execute()) {
                            $response['success'] = true;
                            $response['message'] = $_L['resubmit_success'];
                            // Attempt to delete old file
                            if (file_exists($existing_submission_path)) {
                                unlink($existing_submission_path); // Delete old file
                            }
                        } else {
                            error_log("DB error on submission update: " . $stmt_update->error);
                            $response['message'] = $_L['upload_error'] . " (DB Update Error)";
                        }
                        $stmt_update->close();
                    } else {
                        error_log("DB prepare error on submission update: " . $conn->error);
                        $response['message'] = $_L['upload_error'] . " (DB Prepare Error)";
                    }
                } else {
                    // Insert new submission
                    $sql_insert_submission = "INSERT INTO assignment_submissions (assignment_id, student_id, submission_path, submitted_at, is_resubmission) VALUES (?, ?, ?, NOW(), 0)";
                    if ($stmt_insert = $conn->prepare($sql_insert_submission)) {
                        $stmt_insert->bind_param("iis", $assignment_id, $student_user_id, $destination_path);
                        if ($stmt_insert->execute()) {
                            $response['success'] = true;
                            $response['message'] = $_L['upload_success'];
                        } else {
                            error_log("DB error on submission insert: " . $stmt_insert->error);
                            $response['message'] = $_L['upload_error'] . " (DB Insert Error)";
                        }
                        $stmt_insert->close();
                    } else {
                        error_log("DB prepare error on submission insert: " . $conn->error);
                        $response['message'] = $_L['upload_error'] . " (DB Prepare Error)";
                    }
                }
            } else {
                $response['message'] = $_L['upload_error'] . " (File Move Failed)";
            }
        }
    } else {
        $response['message'] = $_L['no_file_selected'];
        if ($_FILES['assignment_file']['error'] !== UPLOAD_ERR_NO_FILE) {
             error_log("File upload error: " . $_FILES['assignment_file']['error']);
             $response['message'] = $_L['upload_error'] . " (Upload Code: " . $_FILES['assignment_file']['error'] . ")";
        }
    }
    echo json_encode($response);
    if (isset($conn) && $conn instanceof mysqli) {
        $conn->close();
    }
    exit;
}

// Fetch student and school data for header display
if (isset($conn) && $conn instanceof mysqli) {
    $sql_student_details = "SELECT photo FROM users WHERE id = ?";
    if ($stmt_student = $conn->prepare($sql_student_details)) {
        $stmt_student->bind_param("i", $student_user_id);
        if ($stmt_student->execute()) {
            $stmt_student->bind_result($photo_db);
            if ($stmt_student->fetch()) {
                $student_photo = !empty($photo_db) ? htmlspecialchars($photo_db) : 'images/default_student_photo.png';
            }
        }
        $stmt_student->close();
    }

    $sql_school_details = "SELECT school_name, logo FROM schools WHERE school_id = ?";
    if ($stmt_school = $conn->prepare($sql_school_details)) {
        $stmt_school->bind_param("i", $school_id);
        if ($stmt_school->execute()) {
            $stmt_school->bind_result($school_name_db, $school_logo_db);
            if ($stmt_school->fetch()) {
                $school_name = htmlspecialchars($school_name_db);
                $school_logo_path = !empty($school_logo_db) ? htmlspecialchars($school_logo_db) : 'images/default_school_logo.png';
            }
        }
        $stmt_school->close();
    }

    $studentAssignments = [];
    $student_stream_id = null;

    // FIXED: Get stream_id directly from users table (not from students table which is empty)
    $sql_student_stream = "SELECT stream_id FROM users WHERE id = ? AND school_id = ? AND role = ?";
    if ($stmt_student_stream = $conn->prepare($sql_student_stream)) {
        $student_role = ROLE_STUDENT;
        $stmt_student_stream->bind_param("iii", $student_user_id, $school_id, $student_role);
        if ($stmt_student_stream->execute()) {
            $result_student_stream = $stmt_student_stream->get_result();
            if ($row_stream = $result_student_stream->fetch_assoc()) {
                $student_stream_id = $row_stream['stream_id'];
            } else {
                error_log("No stream_id found for student user_id: $student_user_id");
            }
        } else {
            error_log("Execute failed for student stream query: " . $stmt_student_stream->error);
        }
        $stmt_student_stream->close();
    } else {
        error_log("Prepare failed for student stream query: " . $conn->error);
    }

    if ($student_stream_id !== null) {
        $sql_assignments = "
            SELECT
                a.assignment_id,
                a.title,
                a.description,
                a.due_date,
                sub.subject_name,
                u.username AS teacher_name
            FROM
                assignments a
            JOIN
                subjects sub ON a.subject_id = sub.subject_id
            JOIN
                users u ON a.teacher_user_id = u.id
            WHERE
                a.school_id = ? AND a.stream_id = ?
            ORDER BY
                a.due_date ASC;
        ";
        if ($stmt_assignments = $conn->prepare($sql_assignments)) {
            $stmt_assignments->bind_param("ii", $school_id, $student_stream_id);
            if ($stmt_assignments->execute()) {
                $result_assignments = $stmt_assignments->get_result();
                while ($row = $result_assignments->fetch_assoc()) {
                    // Check if student has submitted this assignment
                    $sql_check_submission = "SELECT submission_id FROM assignment_submissions WHERE assignment_id = ? AND student_id = ?";
                    $is_submitted = false;
                    if ($stmt_check = $conn->prepare($sql_check_submission)) {
                        $stmt_check->bind_param("ii", $row['assignment_id'], $student_user_id);
                        $stmt_check->execute();
                        $stmt_check->store_result();
                        if ($stmt_check->num_rows > 0) {
                            $is_submitted = true;
                        }
                        $stmt_check->close();
                    }
                    $row['is_submitted'] = $is_submitted;
                    $studentAssignments[] = $row;
                }
            } else {
                error_log("Execute failed for assignments query: " . $stmt_assignments->error);
            }
            $stmt_assignments->close();
        } else {
            error_log("Prepare failed for assignments query: " . $conn->error);
        }
    } else {
        error_log("Student stream_id is NULL for user_id: $student_user_id - user may not be assigned to a stream. No assignments fetched.");
    }

    $conn->close();
} else {
    error_log("Database connection \$conn not available in student_assignments.php");
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $_L['sidebar_assignments']; ?> - <?php echo $school_name; ?></title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="<?php echo $school_logo_path; ?>" type="image/png">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        /* Fixed Header and Sidebar Styles */
        .dashboard-container {
            display: flex;
            height: 100vh;
            overflow: hidden;
        }

        .sidebar {
            position: fixed;
            left: 0;
            top: 0;
            height: 100vh;
            width: 250px;
            overflow-y: auto;
            z-index: 1000;
            box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
        }

        .main-content {
            margin-left: 250px;
            width: calc(100% - 250px);
            height: 100vh;
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        .header {
            position: fixed;
            top: 0;
            left: 250px;
            right: 0;
            z-index: 999;
            background-color: #ffffff;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        /* Scrollable content area with fade effect */
        .content-wrapper {
            flex: 1;
            overflow-y: auto;
            overflow-x: hidden;
            margin-top: 80px; /* Adjust based on header height */
            position: relative;
        }

        /* Fade overlay at the top */
        .content-wrapper::before {
            content: '';
            position: sticky;
            top: 0;
            left: 0;
            right: 0;
            height: 40px;
            background: linear-gradient(to bottom, rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0) 100%);
            pointer-events: none;
            z-index: 10;
        }

        /* Smooth scrolling */
        .content-wrapper {
            scroll-behavior: smooth;
        }

        /* Custom scrollbar */
        .content-wrapper::-webkit-scrollbar {
            width: 8px;
        }

        .content-wrapper::-webkit-scrollbar-track {
            background: #f1f1f1;
        }

        .content-wrapper::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 4px;
        }

        .content-wrapper::-webkit-scrollbar-thumb:hover {
            background: #555;
        }

        /* Responsive adjustments */
        @media (max-width: 768px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease-in-out;
            }

            .sidebar.active {
                transform: translateX(0);
            }

            .main-content {
                margin-left: 0;
                width: 100%;
            }

            .header {
                left: 0;
            }
        }

        .modern-table-container {
            border-collapse: separate;
            border-spacing: 0;
            overflow: hidden;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
            border-radius: 0.75rem;
        }
        .modern-table-container th,
        .modern-table-container td {
            padding: 1rem 1.5rem;
            text-align: left;
            border-bottom: 1px solid #e2e8f0;
        }
        .modern-table-container thead th {
            background-color: #f8fafc;
            color: #475569;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.05em;
            font-size: 0.875rem;
        }
        .modern-table-container tbody tr:last-child td {
            border-bottom: none;
        }
        .modern-table-container tbody tr:hover {
            background-color: #f0f8ff;
            transition: background-color 0.2s ease-in-out;
        }
        .modern-table-container tbody td {
            color: #334155;
            font-size: 0.95rem;
        }
        .modern-table-container tbody tr td[colspan] {
            font-style: italic;
            color: #64748b;
            text-align: center;
            padding: 1.5rem;
        }
        .overflow-x-auto {
            width: 100%;
        }

        /* Modal specific styles */
        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            opacity: 0;
            visibility: hidden;
            transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
        }
        .modal.show {
            opacity: 1;
            visibility: visible;
        }
        .modal-content {
            background-color: #ffffff;
            padding: 2rem;
            border-radius: 0.75rem;
            box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
            width: 90%;
            max-width: 500px;
            transform: translateY(-20px);
            transition: transform 0.3s ease-in-out;
        }
        .modal.show .modal-content {
            transform: translateY(0);
        }
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            border-bottom: 1px solid #e2e8f0;
            padding-bottom: 1rem;
        }
        .modal-header h2 {
            font-size: 1.75rem;
            font-weight: bold;
            color: #1e293b;
        }
        .modal-close-button {
            background: none;
            border: none;
            font-size: 1.5rem;
            cursor: pointer;
            color: #64748b;
        }
        .modal-body label {
            display: block;
            font-size: 1rem;
            color: #334155;
            font-weight: 500;
            margin-bottom: 0.5rem;
        }
        .modal-body input[type="file"] {
            display: block;
            width: 100%;
            padding: 0.75rem 1rem;
            border: 1px solid #cbd5e0;
            border-radius: 0.375rem;
            font-size: 1rem;
            color: #334155;
            background-color: #ffffff;
            transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
        }
        .modal-body input[type="file"]:focus {
            outline: none;
            border-color: #3b82f6;
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.25);
        }
        .modal-footer {
            padding-top: 1.5rem;
            text-align: right;
        }
        .btn-submit-modal {
            background-color: #2563eb;
            color: #ffffff;
            padding: 0.75rem 1.5rem;
            border-radius: 0.5rem;
            font-weight: 600;
            transition: background-color 0.15s ease-in-out;
        }
        .btn-submit-modal:hover {
            background-color: #1d4ed8;
        }
        /* FIXED: Properly defined all message-box style states */
        .message-box {
            padding: 0.75rem 1rem;
            border-radius: 0.375rem;
            margin-top: 1rem;
            font-size: 0.9rem;
            display: none; /* Hidden by default */
        }
        .message-box.success {
            background-color: #f0fdf4; /* Green for success */
            color: #15803d;
            border: 1px solid #4ade80;
        }
        .message-box.error {
            background-color: #fef2f2; /* Red for error */
            color: #dc2626;
            border: 1px solid #f87171;
        }
        .message-box.info { /* For "Uploading..." or other neutral messages */
            background-color: #e0f2fe;
            color: #0c4a6e;
            border: 1px solid #7dd3fc;
        }
    </style>
</head>
<body>
    <div class="dashboard-container" id="dashboardContainer">
        <aside class="sidebar" id="sidebar">
            <div class="logo">
                <img src="images/logo.png" alt="divine Logo">
                <?php echo $_L['divine_reports']; ?>
            </div>
            <nav>
                <ul>
                    <li class="<?php echo ($currentPage == 'dashboard' ? 'active' : ''); ?>"><a href="student_dashboard.php"><i class="fas fa-th-large"></i> <?php echo $_L['sidebar_dashboard']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'profile' ? 'active' : ''); ?>"><a href="student_profile.php"><i class="fas fa-user-circle"></i> <?php echo $_L['sidebar_profile']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'reports' ? 'active' : ''); ?>"><a href="student_reports.php"><i class="fas fa-file-invoice"></i> <?php echo $_L['sidebar_reports']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'assignments' ? 'active' : ''); ?>"><a href="student_assignments.php"><i class="fas fa-file-alt"></i> <?php echo $_L['sidebar_assignments']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'messages' ? 'active' : ''); ?>"><a href="student_messages.php"><i class="fas fa-envelope"></i> <?php echo $_L['sidebar_messages']; ?></a></li>
                    <li class="<?php echo ($currentPage == 'settings' ? 'active' : ''); ?>"><a href="student_settings.php"><i class="fas fa-cog"></i> <?php echo $_L['sidebar_settings']; ?></a></li>
                    <li><a href="logout.php"><i class="fas fa-sign-out-alt"></i> <?php echo $_L['sidebar_logout']; ?></a></li>
                </ul>
            </nav>
        </aside>

        <div class="main-content">
            <header class="header">
                <button class="menu-toggle" id="menuToggle">
                    <i class="fas fa-bars"></i>
                </button>
                <div class="school-info">
                    <img src="<?php echo $school_logo_path; ?>" alt="<?php echo $school_name; ?> Logo">
                    <h1><?php echo $school_name; ?></h1>
                </div>
                <div class="header-right">
                    <div class="language-select">
                        <select id="languageSelector" onchange="changeLanguage(this.value)">
                           <option value="en" <?php if ($current_lang === 'en') echo 'selected'; ?>>🇬🇧 English</option>
                           <option value="lug" <?php if ($current_lang === 'lug') echo 'selected'; ?>>🇺🇬 Luganda</option>
                           <option value="sw" <?php if ($current_lang === 'sw') echo 'selected'; ?>>🇹🇿 Kiswahili</option>
                        </select>
                    </div>
                    <div class="search-bar">
                        <i class="fas fa-search"></i>
                        <input type="text" placeholder="<?php echo $_L['search_placeholder']; ?>">
                    </div>
                    <div class="notifications">
                        <i class="fas fa-bell"></i>
                        <span class="badge">3</span>
                    </div>
                    <div class="user-profile">
                        <img src="<?php echo $student_photo; ?>" alt="User Photo">
                        <div>
                            <div class="user-name"><?php echo $username; ?></div>
                            <div class="user-email"><?php echo $_L['logged_in_as']; ?> <?php echo $role_name; ?></div>
                        </div>
                        <i class="fas fa-chevron-down"></i>
                    </div>
                </div>
            </header>

            <div class="content-wrapper">
                <div class="container mx-auto p-6 lg:p-8">
                <div class="bg-white rounded-lg shadow-md p-6">
                    <h1 class="text-3xl font-bold text-blue-700 mb-6"><?php echo $_L['assignments_heading']; ?></h1>

                    <!-- Assignments Table -->
                    <div class="overflow-x-auto modern-table-container">
                        <table class="min-w-full bg-white">
                            <thead>
                                <tr>
                                    <th><?php echo $_L['title_column']; ?></th>
                                    <th><?php echo $_L['subject_column']; ?></th>
                                    <th><?php echo $_L['due_date_column']; ?></th>
                                    <th><?php echo $_L['description_column']; ?></th>
                                    <th><?php echo $_L['assigned_by_column']; ?></th>
                                    <th><?php echo $_L['submission_column']; ?></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($studentAssignments)): ?>
                                    <?php foreach ($studentAssignments as $assignment):
                                        $current_time = new DateTime();
                                        $due_date_obj = new DateTime($assignment['due_date']);
                                        $is_past_due = $current_time > $due_date_obj;
                                    ?>
                                        <tr data-assignment-id="<?php echo htmlspecialchars($assignment['assignment_id']); ?>" data-due-date="<?php echo htmlspecialchars($assignment['due_date']); ?>" data-is-submitted="<?php echo $assignment['is_submitted'] ? 'true' : 'false'; ?>">
                                            <td><?php echo htmlspecialchars($assignment['title']); ?></td>
                                            <td><?php echo htmlspecialchars($assignment['subject_name']); ?></td>
                                            <td>
                                                <span class="due-date-display"><?php echo htmlspecialchars($assignment['due_date']); ?></span><br>
                                                <span class="countdown-timer text-sm font-semibold
                                                    <?php echo $is_past_due ? 'text-gray-500 italic' : 'text-red-600'; ?>">
                                                    <?php echo $is_past_due ? $_L['countdown_past_due'] : $_L['countdown_prefix'] . ' Calculating...'; ?>
                                                </span>
                                            </td>
                                            <td><?php echo htmlspecialchars($assignment['description'] ?: 'N/A'); ?></td>
                                            <td><?php echo htmlspecialchars($assignment['teacher_name']); ?></td>
                                            <td>
                                                <?php if (!$assignment['is_submitted']): ?>
                                                    <?php if (!$is_past_due): ?>
                                                        <button class="bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded-md text-sm upload-btn" data-assignment-id="<?php echo htmlspecialchars($assignment['assignment_id']); ?>" data-assignment-title="<?php echo htmlspecialchars($assignment['title']); ?>">
                                                            <i class="fas fa-upload mr-1"></i> <?php echo $_L['upload_assignment']; ?>
                                                        </button>
                                                    <?php else: ?>
                                                        <span class="text-gray-500 font-semibold"><?php echo $_L['unsubmitted_status']; ?></span>
                                                    <?php endif; ?>
                                                <?php else: /* Assignment is submitted */ ?>
                                                    <?php if (!$is_past_due): ?>
                                                        <button class="bg-purple-600 hover:bg-purple-700 text-white font-semibold py-2 px-4 rounded-md text-sm upload-btn" data-assignment-id="<?php echo htmlspecialchars($assignment['assignment_id']); ?>" data-assignment-title="<?php echo htmlspecialchars($assignment['title']); ?>">
                                                            <i class="fas fa-edit mr-1"></i> <?php echo $_L['edit_submission']; ?>
                                                        </button>
                                                    <?php else: ?>
                                                        <span class="text-green-600 font-semibold"><i class="fas fa-check-circle mr-1"></i> <?php echo $_L['already_submitted_past_due']; ?></span>
                                                    <?php endif; ?>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="6" class="text-center text-gray-500 py-4">
                                            <?php echo $_L['no_assignments_found']; ?>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            </div>
        </div>
    </div>

    <!-- Assignment Upload Modal -->
    <div id="uploadAssignmentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalAssignmentTitle"></h2>
                <button class="modal-close-button" id="closeModalBtn">&times;</button>
            </div>
            <div class="modal-body">
                <form id="assignmentUploadForm" enctype="multipart/form-data">
                    <input type="hidden" id="uploadAssignmentId" name="assignment_id">
                    <input type="hidden" name="action" value="submit_assignment">
                    <div class="form-group mb-4">
                        <label for="assignmentFile" class="block text-gray-700 text-sm font-medium mb-2"><?php echo $_L['select_file_label']; ?>:</label>
                        <input type="file" id="assignmentFile" name="assignment_file" accept=".pdf" required>
                        <p class="text-xs text-gray-500 mt-1">Max file size: 5MB. Only PDF files allowed.</p>
                    </div>
                    <div id="uploadMessageBox" class="message-box" style="display: none;"></div>
                    <div class="modal-footer">
                        <button type="submit" class="btn-submit-modal">
                            <i class="fas fa-paper-plane mr-2"></i> <?php echo $_L['submit_button']; ?>
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>


    <script>
        // Language change function
        function changeLanguage(lang) {
            window.location.href = `?lang=${lang}`;
        }

        // Sidebar toggle functionality
        document.addEventListener('DOMContentLoaded', function() {
            const menuToggle = document.getElementById('menuToggle');
            const sidebar = document.getElementById('sidebar');
            const dashboardContainer = document.getElementById('dashboardContainer');

            if (menuToggle && sidebar && dashboardContainer) {
                menuToggle.addEventListener('click', function() {
                    sidebar.classList.toggle('active');
                    dashboardContainer.classList.toggle('sidebar-open');
                });

                dashboardContainer.addEventListener('click', function(event) {
                    if (sidebar.classList.contains('active') && !sidebar.contains(event.target) && !menuToggle.contains(event.target)) {
                        sidebar.classList.remove('active');
                        dashboardContainer.classList.remove('sidebar-open');
                    }
                });
            } else {
                console.error("Menu toggle, sidebar, or dashboard container elements for responsive behavior not found.");
            }

            // --- Countdown Timer Logic ---
            function updateCountdown() {
                const rows = document.querySelectorAll('tbody tr[data-due-date]');
                const now = new Date();

                rows.forEach(row => {
                    const dueDateStr = row.dataset.dueDate;
                    let isSubmitted = row.dataset.isSubmitted === 'true'; // Allow update
                    const countdownTimerSpan = row.querySelector('.countdown-timer');
                    const uploadButton = row.querySelector('.upload-btn'); // Get the upload button for this row
                    const submissionCell = row.querySelector('td:last-child'); // Get the submission cell

                    if (!countdownTimerSpan || !submissionCell) return;

                    const dueDate = new Date(dueDateStr);

                    if (isNaN(dueDate.getTime())) {
                        countdownTimerSpan.textContent = 'Invalid Date';
                        return;
                    }

                    const diff = dueDate.getTime() - now.getTime(); // Difference in milliseconds
                    const isPastDue = diff <= 0;

                    if (isPastDue) {
                        countdownTimerSpan.textContent = "<?php echo $_L['countdown_past_due']; ?>";
                        countdownTimerSpan.classList.remove('text-red-600', 'font-semibold');
                        countdownTimerSpan.classList.add('text-gray-500', 'italic');

                        if (uploadButton) {
                            uploadButton.disabled = true;
                            uploadButton.classList.remove('bg-blue-500', 'hover:bg-blue-600', 'bg-purple-600', 'hover:bg-purple-700');
                            uploadButton.classList.add('bg-gray-400', 'cursor-not-allowed');
                        }
                        // Update status text in the submission cell if past due
                        if (!isSubmitted) {
                             submissionCell.innerHTML = `<span class="text-gray-500 font-semibold"><?php echo $_L['unsubmitted_status']; ?></span>`;
                        } else {
                            submissionCell.innerHTML = `<span class="text-green-600 font-semibold"><i class="fas fa-check-circle mr-1"></i> <?php echo $_L['already_submitted_past_due']; ?></span>`;
                        }

                    } else { // Still within due date
                        const seconds = Math.floor((diff / 1000) % 60);
                        const minutes = Math.floor((diff / (1000 * 60)) % 60);
                        const hours = Math.floor((diff / (1000 * 60 * 60)) % 24);
                        const days = Math.floor(diff / (1000 * 60 * 60 * 24));

                        let countdownText = "<?php echo $_L['countdown_prefix']; ?> ";
                        if (days > 0) countdownText += `${days}d `;
                        countdownText += `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;

                        countdownTimerSpan.textContent = countdownText;
                        countdownTimerSpan.classList.add('text-red-600', 'font-semibold');
                        countdownTimerSpan.classList.remove('text-gray-500', 'italic');

                        // Re-enable button and set appropriate text/color if within due date
                        if (uploadButton) {
                            uploadButton.disabled = false;
                            if (isSubmitted) {
                                uploadButton.classList.remove('bg-blue-500', 'hover:bg-blue-600', 'bg-gray-400', 'cursor-not-allowed');
                                uploadButton.classList.add('bg-purple-600', 'hover:bg-purple-700');
                                uploadButton.innerHTML = `<i class="fas fa-edit mr-1"></i> <?php echo $_L['edit_submission']; ?>`;
                            } else {
                                uploadButton.classList.remove('bg-purple-600', 'hover:bg-purple-700', 'bg-gray-400', 'cursor-not-allowed');
                                uploadButton.classList.add('bg-blue-500', 'hover:bg-blue-600');
                                uploadButton.innerHTML = `<i class="fas fa-upload mr-1"></i> <?php echo $_L['upload_assignment']; ?>`;
                            }
                        }
                    }
                });
            }

            setInterval(updateCountdown, 1000);
            updateCountdown();

            // --- Assignment Upload Modal Logic ---
            const uploadModal = document.getElementById('uploadAssignmentModal');
            const closeModalBtn = document.getElementById('closeModalBtn');
            // Use event delegation for buttons as they can be dynamically updated
            document.querySelector('tbody').addEventListener('click', function(event) {
                if (event.target.classList.contains('upload-btn')) {
                    const btn = event.target;
                    const assignmentId = btn.dataset.assignmentId;
                    const assignmentTitle = btn.dataset.assignmentTitle;
                    uploadAssignmentId.value = assignmentId;
                    modalAssignmentTitle.textContent = `${assignmentTitle} - ${btn.textContent.trim()}`; // Use button's current text
                    uploadMessageBox.style.display = 'none'; // Hide message box on open
                    uploadMessageBox.className = 'message-box'; // Reset classes
                    assignmentFile.value = ''; // Clear file input
                    uploadModal.classList.add('show');
                }
            });

            closeModalBtn.addEventListener('click', () => {
                uploadModal.classList.remove('show');
            });

            window.addEventListener('click', (event) => {
                if (event.target === uploadModal) {
                    uploadModal.classList.remove('show');
                }
            });

            assignmentUploadForm.addEventListener('submit', function(e) {
                e.preventDefault();

                const formData = new FormData(this);

                uploadMessageBox.textContent = "<?php echo $_L['uploading_message']; ?>";
                uploadMessageBox.classList.add('info');
                uploadMessageBox.style.display = 'block';

                const fileInput = document.getElementById('assignmentFile');
                if (fileInput.files.length > 0) {
                    const file = fileInput.files[0];
                    const fileExtension = file.name.split('.').pop().toLowerCase();
                    const allowedExtensions = ['pdf'];
                    const maxFileSize = 5 * 1024 * 1024; // 5MB

                    if (!allowedExtensions.includes(fileExtension)) {
                        uploadMessageBox.textContent = "<?php echo $_L['file_type_error']; ?>";
                        uploadMessageBox.classList.remove('info');
                        uploadMessageBox.classList.add('error');
                        return;
                    }
                    if (file.size > maxFileSize) {
                        uploadMessageBox.textContent = "<?php echo $_L['file_size_error']; ?>";
                        uploadMessageBox.classList.remove('info');
                        uploadMessageBox.classList.add('error');
                        return;
                    }
                } else {
                    uploadMessageBox.textContent = "<?php echo $_L['no_file_selected']; ?>";
                    uploadMessageBox.classList.remove('info');
                    uploadMessageBox.classList.add('error');
                    return;
                }

                fetch('student_assignments.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => response.json())
                .then(data => {
                    uploadMessageBox.textContent = data.message;
                    if (data.success) {
                        uploadMessageBox.classList.remove('info', 'error');
                        uploadMessageBox.classList.add('success');
                        const submittedAssignmentId = uploadAssignmentId.value;
                        const row = document.querySelector(`tr[data-assignment-id="${submittedAssignmentId}"]`);
                        if (row) {
                            row.dataset.isSubmitted = 'true'; // Mark as submitted
                            // Update the countdown timer and button status immediately
                            updateCountdown();
                        }
                        setTimeout(() => uploadModal.classList.remove('show'), 2000);
                    } else {
                        uploadMessageBox.classList.remove('info');
                        uploadMessageBox.classList.add('error');
                    }
                })
                .catch(error => {
                    console.error('Upload Error:', error);
                    uploadMessageBox.textContent = "<?php echo $_L['upload_error']; ?>: " + error.message;
                    uploadMessageBox.classList.remove('info');
                    uploadMessageBox.classList.add('error');
                });
            });
        });
    </script>
</body>
</html>
