<?php
session_start();
require_once '../config/database.php';
require_once '../includes/sidebar_layout.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ../login.php');
    exit();
}

$user_role = $_SESSION['user_role'];
$user_name = $_SESSION['user_name'];

// Fetch classes and subjects for dropdowns
try {
    // Fetch all active classes
    $stmt = $pdo->query("SELECT id, name, section FROM classes WHERE status = 'active' ORDER BY name");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch all active subjects
    $stmt = $pdo->query("SELECT id, name FROM subjects WHERE status = 'active' ORDER BY name");
    $subjects = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $classes = [];
    $subjects = [];
    error_log("Error fetching classes/subjects: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>অ্যাসাইনমেন্ট - অনলাইন শিক্ষা</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/jessoreboard-theme.css" rel="stylesheet">
    <link href="../assets/css/sidebar.css" rel="stylesheet">
    <style>
        .assignment-card {
            border-radius: 15px;
            overflow: hidden;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .assignment-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .assignment-header {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
            padding: 20px;
        }
        
        .assignment-body {
            padding: 20px;
        }
        
        .assignment-footer {
            background-color: #f8f9fa;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
        }
        
        .status-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        
        .status-submitted {
            background-color: #d4edda;
            color: #155724;
        }
        
        .status-graded {
            background-color: #d1ecf1;
            color: #0c5460;
        }
        
        .upload-area {
            border: 2px dashed #ccc;
            border-radius: 10px;
            padding: 30px;
            text-align: center;
            margin-bottom: 20px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        
        .upload-area:hover {
            border-color: #667eea;
            background-color: #f8f9ff;
        }
        
        .file-list {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            margin-bottom: 20px;
        }
        
        .file-item {
            display: flex;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .file-icon {
            font-size: 1.5rem;
            margin-right: 10px;
            color: #667eea;
        }
        
        .submission-history {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 15px;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .submission-item {
            padding: 10px;
            border-bottom: 1px solid #e0e0e0;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="sidebar-container">
        <?php echo renderSidebar('online_learning/assignments.php', $user_role, $user_name); ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-tasks me-2"></i>
                    অ্যাসাইনমেন্ট
                </h1>
                <p class="content-breadcrumb">
                    <i class="fas fa-home me-1"></i>
                    হোম / অনলাইন শিক্ষা / অ্যাসাইনমেন্ট
                </p>
            </div>
            
            <!-- Content Body -->
            <div class="content-body">
                <?php if ($user_role == 'admin' || $user_role == 'teacher'): ?>
                <!-- Teacher/Admin View -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-plus-circle me-2"></i>
                                    নতুন অ্যাসাইনমেন্ট তৈরি
                                </h5>
                            </div>
                            <div class="card-body">
                                <form id="assignmentForm">
                                    <div class="mb-3">
                                        <label class="form-label">অ্যাসাইনমেন্টের শিরোনাম</label>
                                        <input type="text" class="form-control" name="title" placeholder="অ্যাসাইনমেন্টের শিরোনাম লিখুন" required>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">বিষয়</label>
                                                <select class="form-select" name="subject_id" required>
                                                    <option value="">বিষয় নির্বাচন করুন</option>
                                                    <?php foreach ($subjects as $subject): ?>
                                                        <option value="<?php echo $subject['id']; ?>"><?php echo htmlspecialchars($subject['name']); ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">ক্লাস</label>
                                                <select class="form-select" name="class_id" required>
                                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?php echo $class['id']; ?>"><?php echo htmlspecialchars($class['name'] . ' - ' . $class['section']); ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">বর্ণনা</label>
                                        <textarea class="form-control" name="description" rows="4" placeholder="অ্যাসাইনমেন্টের বর্ণনা লিখুন"></textarea>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">জমা দেওয়ার শেষ তারিখ</label>
                                                <input type="datetime-local" class="form-control" name="due_date" required>
                                            </div>
                                        </div>
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">মোট নম্বর</label>
                                                <input type="number" class="form-control" name="max_marks" placeholder="মোট নম্বর লিখুন" value="20">
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">নির্দেশাবলী</label>
                                        <textarea class="form-control" name="instructions" rows="3" placeholder="ছাত্র-ছাত্রীদের জন্য নির্দেশাবলী"></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">ফাইল আপলোড (ঐচ্ছিক)</label>
                                        <input type="file" class="form-control" name="attachment">
                                        <div class="form-text">প্রশ্নপত্র বা অন্যান্য সম্পর্কিত ফাইল আপলোড করুন</div>
                                    </div>
                                    
                                    <button type="submit" class="btn btn-primary" id="publishBtn">
                                        <i class="fas fa-paper-plane me-2"></i>
                                        <span id="publishBtnText">অ্যাসাইনমেন্ট প্রকাশ করুন</span>
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-cog me-2"></i>
                                    সেটিংস
                                </h5>
                            </div>
                            <div class="card-body">
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="allowLateSubmission">
                                    <label class="form-check-label" for="allowLateSubmission">
                                        দেরিতে জমা দেওয়ার অনুমতি
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="allowResubmission">
                                    <label class="form-check-label" for="allowResubmission">
                                        পুনরায় জমা দেওয়ার অনুমতি
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="plagiarismCheck">
                                    <label class="form-check-label" for="plagiarismCheck">
                                        প্লাজিয়ারিজম চেক করুন
                                    </label>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">প্লাজিয়ারিজম সীমা (%)</label>
                                    <input type="number" class="form-control" placeholder="সীমা লিখুন" value="20">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <!-- Student View - Assignment Submission -->
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header bg-primary text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-file-upload me-2"></i>
                                    অ্যাসাইনমেন্ট জমা দিন
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php
                                // Fetch the most recent assignment for this student's class
                                try {
                                    $stmt = $pdo->prepare("
                                        SELECT a.*, s.name as subject_name 
                                        FROM assignments a
                                        JOIN subjects s ON a.subject_id = s.id
                                        WHERE a.class_id = (SELECT class_id FROM students WHERE user_id = ?)
                                        AND a.status = 'published'
                                        ORDER BY a.created_at DESC
                                        LIMIT 1
                                    ");
                                    $stmt->execute([$_SESSION['user_id']]);
                                    $currentAssignment = $stmt->fetch(PDO::FETCH_ASSOC);
                                    
                                    if ($currentAssignment):
                                ?>
                                <h5><?php echo htmlspecialchars($currentAssignment['subject_name'] . ' - ' . $currentAssignment['title']); ?></h5>
                                <p>জমা দেওয়ার শেষ তারিখ: <?php echo date('d F, Y, g:i A', strtotime($currentAssignment['due_date'])); ?></p>
                                
                                <div class="upload-area" id="uploadArea">
                                    <i class="fas fa-cloud-upload-alt fa-3x mb-3"></i>
                                    <h5>ফাইল আপলোড করুন</h5>
                                    <p>ফাইল টেনে আনুন অথবা ক্লিক করে নির্বাচন করুন</p>
                                    <input type="file" id="fileInput" class="d-none" multiple>
                                </div>
                                
                                <div class="file-list" id="fileList" style="display: none;">
                                    <h6>নির্বাচিত ফাইলসমূহ:</h6>
                                    <div id="fileItems"></div>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">মন্তব্য (ঐচ্ছিক)</label>
                                    <textarea class="form-control" name="comments" rows="3" placeholder="শিক্ষকের জন্য কোন মন্তব্য থাকলে লিখুন"></textarea>
                                </div>
                                
                                <button class="btn btn-success" id="mainSubmitBtn" data-assignment-id="<?php echo $currentAssignment['id']; ?>">
                                    <i class="fas fa-paper-plane me-2"></i>
                                    অ্যাসাইনমেন্ট জমা দিন
                                </button>
                                <?php else: ?>
                                <p>আপনার জন্য কোন অ্যাসাইনমেন্ট পাওয়া যায়নি।</p>
                                <?php endif; ?>
                                <?php } catch (Exception $e) { ?>
                                <p>তথ্য লোড করতে সমস্যা হয়েছে।</p>
                                <?php } ?>
                            </div>
                        </div>
                    </div>
                    
                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header bg-info text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-history me-2"></i>
                                    জমা দেওয়া ইতিহাস
                                </h5>
                            </div>
                            <div class="submission-history">
                                <?php
                                // Fetch submission history for this student
                                try {
                                    $stmt = $pdo->prepare("
                                        SELECT asub.*, a.title as assignment_title, s.name as subject_name 
                                        FROM assignment_submissions asub
                                        JOIN assignments a ON asub.assignment_id = a.id
                                        JOIN subjects s ON a.subject_id = s.id
                                        WHERE asub.student_id = (SELECT id FROM students WHERE user_id = ?)
                                        ORDER BY asub.submission_date DESC
                                        LIMIT 5
                                    ");
                                    $stmt->execute([$_SESSION['user_id']]);
                                    $submissions = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                    
                                    if (count($submissions) > 0):
                                        foreach ($submissions as $submission):
                                ?>
                                <div class="submission-item">
                                    <div><strong>জমা দেওয়ার তারিখ:</strong> <?php echo date('d F, Y', strtotime($submission['submission_date'])); ?></div>
                                    <div><strong>বিষয়:</strong> <?php echo htmlspecialchars($submission['subject_name']); ?></div>
                                    <div><strong>অবস্থা:</strong> <span class="status-badge status-submitted">জমা দেওয়া হয়েছে</span></div>
                                </div>
                                <?php 
                                        endforeach;
                                    else:
                                ?>
                                <div class="submission-item">
                                    <div>আপনি এখনো কোন অ্যাসাইনমেন্ট জমা দেননি।</div>
                                </div>
                                <?php 
                                    endif;
                                } catch (Exception $e) { ?>
                                <div class="submission-item">
                                    <div>জমা দেওয়ার ইতিহাস লোড করতে সমস্যা হয়েছে।</div>
                                </div>
                                <?php } ?>
                            </div>
                        </div>
                        
                        <div class="card mt-4">
                            <div class="card-header bg-success text-white">
                                <h5 class="mb-0">
                                    <i class="fas fa-file-download me-2"></i>
                                    অ্যাসাইনমেন্ট ফাইল
                                </h5>
                            </div>
                            <div class="card-body">
                                <?php
                                // Show files for the current assignment if it exists
                                if (isset($currentAssignment) && $currentAssignment):
                                    // Check if assignment has an attachment
                                    if ($currentAssignment['file_upload_id']):
                                        try {
                                            // Fetch file information
                                            $stmt = $pdo->prepare("
                                                SELECT fu.*, 
                                                       CASE 
                                                           WHEN fu.uploader_type = 'student' THEN CONCAT(s.first_name, ' ', s.last_name)
                                                           WHEN fu.uploader_type = 'teacher' THEN CONCAT(t.first_name, ' ', t.last_name)
                                                           ELSE 'Admin'
                                                       END as uploader_name
                                                FROM file_uploads fu
                                                LEFT JOIN students s ON fu.uploader_type = 'student' AND fu.uploader_id = s.id
                                                LEFT JOIN teachers t ON fu.uploader_type = 'teacher' AND fu.uploader_id = t.id
                                                WHERE fu.id = ? AND fu.status = 'active'
                                            ");
                                            $stmt->execute([$currentAssignment['file_upload_id']]);
                                            $assignmentFile = $stmt->fetch();
                                            
                                            if ($assignmentFile):
                                            ?>
                                            <div class="d-flex align-items-center mb-3">
                                                <div class="me-3">
                                                    <i class="fas fa-file fa-2x text-primary"></i>
                                                </div>
                                                <div class="flex-grow-1">
                                                    <h6 class="mb-0"><?php echo htmlspecialchars($assignmentFile['original_name']); ?></h6>
                                                    <small class="text-muted">
                                                        Uploaded by: <?php echo htmlspecialchars($assignmentFile['uploader_name']); ?> | 
                                                        Size: <?php echo round($assignmentFile['file_size'] / 1024, 1); ?> KB | 
                                                        Type: <?php echo htmlspecialchars($assignmentFile['file_type']); ?>
                                                    </small>
                                                </div>
                                                <div>
                                                    <a href="../uploads/download.php?id=<?php echo $assignmentFile['id']; ?>" class="btn btn-sm btn-primary">
                                                        <i class="fas fa-download me-1"></i> ডাউনলোড
                                                    </a>
                                                </div>
                                            </div>
                                            <?php
                                            else:
                                            ?>
                                            <p>ফাইল পাওয়া যায়নি।</p>
                                            <?php
                                            endif;
                                        } catch (Exception $e) {
                                            echo '<p>ফাইল তথ্য লোড করতে সমস্যা হয়েছে।</p>';
                                            error_log("Error fetching assignment file: " . $e->getMessage());
                                        }
                                    else:
                                    ?>
                                    <p>এই অ্যাসাইনমেন্টের সাথে কোন ফাইল সংযুক্ত করা হয়নি।</p>
                                    <?php
                                    endif;
                                else:
                                ?>
                                <p>কোন অ্যাসাইনমেন্ট ফাইল পাওয়া যায়নি।</p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                

                
                <!-- Assignment List -->
                <div class="card mt-4">
                    <div class="card-header bg-warning text-white">
                        <h5 class="mb-0">
                            <i class="fas fa-list me-2"></i>
                            অ্যাসাইনমেন্ট তালিকা
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>শিরোনাম</th>
                                        <th>বিষয়</th>
                                        <th>ক্লাস</th>
                                        <th>জমা দেওয়ার শেষ তারিখ</th>
                                        <th>অবস্থা</th>
                                        <th>কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    // Debug: Show user role
                                    echo '<!-- User role: ' . $user_role . ' -->';
                                    
                                    try {
                                        // Fetch assignments based on user role
                                        if ($user_role == 'admin' || $user_role == 'teacher') {
                                            // For teachers/admins, get all assignments
                                            $stmt = $pdo->prepare("
                                                SELECT a.*, c.name as class_name, c.section as class_section, s.name as subject_name 
                                                FROM assignments a
                                                JOIN classes c ON a.class_id = c.id
                                                JOIN subjects s ON a.subject_id = s.id
                                                ORDER BY a.created_at DESC
                                                LIMIT 20
                                            ");
                                            $stmt->execute();
                                        } else {
                                            // For students, get assignments for their class
                                            $stmt = $pdo->prepare("
                                                SELECT a.*, c.name as class_name, c.section as class_section, s.name as subject_name 
                                                FROM assignments a
                                                JOIN classes c ON a.class_id = c.id
                                                JOIN subjects s ON a.subject_id = s.id
                                                WHERE a.class_id = (SELECT class_id FROM students WHERE user_id = ?)
                                                AND a.status = 'published'
                                                ORDER BY a.created_at DESC
                                                LIMIT 20
                                            ");
                                            $stmt->execute([$_SESSION['user_id']]);
                                        }
                                        
                                        $assignments = $stmt->fetchAll(PDO::FETCH_ASSOC);
                                        
                                        // Debug: Log assignment count and user role
                                        error_log("User role: " . $user_role . ", Assignments found: " . count($assignments));
                                        
                                        if (count($assignments) > 0) {
                                            foreach ($assignments as $assignment) {
                                                // Format due date
                                                $due_date = date('d F, Y', strtotime($assignment['due_date']));
                                                
                                                // Determine status badge class
                                                $status_class = 'status-pending';
                                                $status_text = 'চলছে';
                                                
                                                if ($assignment['status'] == 'closed') {
                                                    $status_class = 'status-graded';
                                                    $status_text = 'বন্ধ';
                                                } elseif ($assignment['status'] == 'published') {
                                                    $status_class = 'status-pending';
                                                    $status_text = 'চলছে';
                                                }
                                                ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($assignment['title']); ?></td>
                                                    <td><?php echo htmlspecialchars($assignment['subject_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($assignment['class_name'] . ' - ' . $assignment['class_section']); ?></td>
                                                    <td><?php echo $due_date; ?></td>
                                                    <td><span class="status-badge <?php echo $status_class; ?>"><?php echo $status_text; ?></span></td>
                                                    <td>
                                                        <?php if ($user_role == 'admin' || $user_role == 'teacher'): ?>
                                                            <!-- Teacher/Admin buttons -->
                                                            <button class="btn btn-sm btn-primary edit-btn" data-assignment-id="<?php echo $assignment['id']; ?>">সম্পাদনা</button>
                                                            <button class="btn btn-sm btn-info view-btn" data-assignment-id="<?php echo $assignment['id']; ?>">জমা দেখুন</button>
                                                            <button class="btn btn-sm btn-danger delete-btn" data-assignment-id="<?php echo $assignment['id']; ?>">মুছুন</button>
                                                        <?php else: ?>
                                                            <!-- Student buttons -->
                                                            <button class="btn btn-sm btn-outline-info" data-assignment-id="<?php echo $assignment['id']; ?>">ফলাফল দেখুন</button>
                                                        <?php endif; ?>
                                                    </td>
                                                </tr>
                                                <?php
                                            }
                                        } else {
                                            echo '<tr><td colspan="6" class="text-center">কোন অ্যাসাইনমেন্ট পাওয়া যায়নি</td></tr>';
                                        }
                                    } catch (Exception $e) {
                                        echo '<tr><td colspan="6" class="text-center">তথ্য লোড করতে সমস্যা হয়েছে</td></tr>';
                                        error_log("Error fetching assignments: " . $e->getMessage());
                                    }
                                    ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // File upload functionality
        document.addEventListener('DOMContentLoaded', function() {
            // Debug: Log when DOM is loaded
            console.log('DOM loaded');
            
            // Handle assignment form submission
            const assignmentForm = document.getElementById('assignmentForm');
            const publishBtn = document.getElementById('publishBtn');
            const publishBtnText = document.getElementById('publishBtnText');
            
            // Add form submission handler
            if (assignmentForm) {
                assignmentForm.addEventListener('submit', function(e) {
                    e.preventDefault();
                    
                    // Show loading state
                    const originalBtnText = publishBtnText.textContent;
                    publishBtnText.textContent = 'Creating...';
                    publishBtn.disabled = true;
                    
                    // Get form data
                    const formData = new FormData(assignmentForm);
                    
                    // Send data to API
                    fetch('api/create_assignment.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            alert('Assignment created successfully!');
                            // Reset form
                            assignmentForm.reset();
                            // Reload page to show new assignment
                            location.reload();
                        } else {
                            alert('Error: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('An error occurred while creating the assignment.');
                    })
                    .finally(() => {
                        // Restore button
                        publishBtnText.textContent = originalBtnText;
                        publishBtn.disabled = false;
                    });
                });
            }
            
            // Store uploaded file ID
            let uploadedFileId = null;
            
            // Debug: Log form elements
            console.log('Assignment form:', assignmentForm);
            console.log('Publish button:', publishBtn);
            
            // Add functionality for assignment list buttons using event delegation
            // Handle all button clicks in the assignment table
            console.log('Initializing button event handlers');
            const table = document.querySelector('table.table');
            console.log('Table element:', table);
            
            // Handle the main submit button in student view
            const mainSubmitBtn = document.getElementById('mainSubmitBtn');
            if (mainSubmitBtn) {
                mainSubmitBtn.addEventListener('click', function() {
                    const assignmentId = this.getAttribute('data-assignment-id');
                    if (!assignmentId) {
                        alert('Assignment ID not found');
                        return;
                    }
                    
                    // Submit assignment via API (file upload is optional)
                    submitAssignment(assignmentId, uploadedFileId, this);
                });
            }
            
            if (table) {
                console.log('Table found, adding event listener');
                table.addEventListener('click', function(e) {
                    console.log('Table clicked, event:', e);
                    const button = e.target.closest('button');
                    console.log('Button found:', button);
                    
                    // Debug: Show all buttons in the table
                    const allButtons = table.querySelectorAll('button');
                    console.log('All buttons in table:', allButtons.length);
                    allButtons.forEach((btn, index) => {
                        console.log(`Button ${index}:`, btn.textContent, btn.className);
                    });
                    
                    if (!button) return;
                    
                    const row = button.closest('tr');
                    console.log('Row found:', row);
                    if (!row) return;
                    
                    const title = row.cells[0] ? row.cells[0].textContent : 'Unknown';
                    const assignmentId = button.getAttribute('data-assignment-id');
                    
                    // Debug: Log button click
                    console.log('Button clicked:', button.textContent, 'Assignment ID:', assignmentId);
                    
                    // Handle edit buttons
                    if (button.classList.contains('edit-btn') || (button.classList.contains('btn-primary') && (button.textContent.trim() === 'সম্পাদনা' || button.innerText.trim() === 'সম্পাদনা'))) {
                        console.log('Edit button clicked');
                        if (!assignmentId) {
                            alert('Assignment ID not found');
                            return;
                        }
                        // Navigate to edit assignment page
                        window.location.href = 'edit_assignment.php?id=' + assignmentId;
                    }
                    
                    // Handle view submission buttons
                    else if (button.classList.contains('view-btn') || (button.classList.contains('btn-info') && (button.textContent.trim() === 'জমা দেখুন' || button.innerText.trim() === 'জমা দেখুন'))) {
                        console.log('View submission button clicked');
                        if (!assignmentId) {
                            alert('Assignment ID not found');
                            return;
                        }
                        // Navigate to view submissions page
                        window.location.href = 'view_submissions.php?id=' + assignmentId;
                    }
                    
                    // Handle delete buttons
                    else if (button.classList.contains('delete-btn') || button.classList.contains('delete-assignment') || (button.classList.contains('btn-danger') && (button.textContent.trim() === 'মুছুন' || button.innerText.trim() === 'মুছুন'))) {
                        console.log('Delete button clicked');
                        if (!assignmentId) {
                            alert('Assignment ID not found');
                            return;
                        }
                        
                        // Confirm deletion
                        if (confirm('Are you sure you want to delete this assignment? This action cannot be undone.')) {
                            deleteAssignment(assignmentId, button);
                        }
                    }
                    
                    // Handle submit buttons
                    else if (button.classList.contains('btn-success') && (button.textContent.trim() === 'জমা দিন' || button.innerText.trim() === 'জমা দিন')) {
                        if (!assignmentId) {
                            alert('Assignment ID not found');
                            return;
                        }
                        
                        // Submit assignment via API (file upload is optional)
                        submitAssignment(assignmentId, uploadedFileId, button);
                    }
                    
                    // Handle view results buttons
                    else if (button.classList.contains('btn-outline-info') && (button.textContent.trim() === 'ফলাফল দেখুন' || button.innerText.trim() === 'ফলাফল দেখুন')) {
                        if (!assignmentId) {
                            alert('Assignment ID not found');
                            return;
                        }
                        // Navigate to view results page
                        window.location.href = 'view_assignment_results.php?id=' + assignmentId;
                    }
                    
                    // Handle disabled submit buttons
                    else if (button.classList.contains('btn-outline-secondary') && (button.textContent.trim() === 'জমা দিন' || button.innerText.trim() === 'জমা দিন')) {
                        alert('This assignment is no longer accepting submissions.');
                    }
                });
            }
            
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');
            const fileList = document.getElementById('fileList');
            const fileItems = document.getElementById('fileItems');
            
            uploadArea.addEventListener('click', function() {
                fileInput.click();
            });
            
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.style.borderColor = '#667eea';
                this.style.backgroundColor = '#f0f4ff';
            });
            
            uploadArea.addEventListener('dragleave', function() {
                this.style.borderColor = '#ccc';
                this.style.backgroundColor = '';
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                this.style.borderColor = '#ccc';
                this.style.backgroundColor = '';
                
                if (e.dataTransfer.files.length) {
                    handleFiles(e.dataTransfer.files);
                }
            });
            
            fileInput.addEventListener('change', function() {
                if (this.files.length) {
                    handleFiles(this.files);
                }
            });
            
            function handleFiles(files) {
                fileList.style.display = 'block';
                fileItems.innerHTML = '';
                
                // Handle file upload to server
                if (files.length > 0) {
                    const file = files[0];
                    
                    // Create FormData object
                    const formData = new FormData();
                    formData.append('assignment_file', file);
                    
                    // Show uploading status
                    const fileItem = document.createElement('div');
                    fileItem.className = 'file-item';
                    fileItem.innerHTML = `
                        <div class="file-icon">
                            <i class="fas fa-spinner fa-spin"></i>
                        </div>
                        <div>
                            <div>${file.name}</div>
                            <small class="text-muted">Uploading...</small>
                        </div>
                    `;
                    fileItems.appendChild(fileItem);
                    
                    // Upload file to server
                    fetch('api/upload_assignment_file.php', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Update file item with success status
                            fileItem.innerHTML = `
                                <div class="file-icon">
                                    <i class="fas fa-file"></i>
                                </div>
                                <div>
                                    <div>${file.name}</div>
                                    <small class="text-muted">${(file.size/1024).toFixed(1)} KB</small>
                                </div>
                                <div class="ms-auto">
                                    <button class="btn btn-sm btn-outline-danger remove-file" data-file-id="${data.file_upload_id}">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            `;
                            
                            // Store the uploaded file ID
                            uploadedFileId = data.file_upload_id;
                            
                            // Add event listener to remove button
                            const removeButton = fileItem.querySelector('.remove-file');
                            removeButton.addEventListener('click', function() {
                                this.closest('.file-item').remove();
                                if (fileItems.children.length === 0) {
                                    fileList.style.display = 'none';
                                }
                                uploadedFileId = 0; // Reset to 0 when no files
                            });
                        } else {
                            // Show error status
                            fileItem.innerHTML = `
                                <div class="file-icon text-danger">
                                    <i class="fas fa-exclamation-circle"></i>
                                </div>
                                <div>
                                    <div>${file.name}</div>
                                    <small class="text-danger">Error: ${data.message}</small>
                                </div>
                                <div class="ms-auto">
                                    <button class="btn btn-sm btn-outline-danger remove-file">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </div>
                            `;
                            
                            // Add event listener to remove button
                            const removeButton = fileItem.querySelector('.remove-file');
                            removeButton.addEventListener('click', function() {
                                this.closest('.file-item').remove();
                                if (fileItems.children.length === 0) {
                                    fileList.style.display = 'none';
                                }
                                uploadedFileId = 0; // Reset to 0 when no files
                            });
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        // Show error status
                        fileItem.innerHTML = `
                            <div class="file-icon text-danger">
                                <i class="fas fa-exclamation-circle"></i>
                            </div>
                            <div>
                                <div>${file.name}</div>
                                <small class="text-danger">Upload failed</small>
                            </div>
                            <div class="ms-auto">
                                <button class="btn btn-sm btn-outline-danger remove-file">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        `;
                        
                        // Add event listener to remove button
                        const removeButton = fileItem.querySelector('.remove-file');
                        removeButton.addEventListener('click', function() {
                            this.closest('.file-item').remove();
                            if (fileItems.children.length === 0) {
                                fileList.style.display = 'none';
                            }
                            uploadedFileId = 0; // Reset to 0 when no files
                        });
                    });
                }
            }
            
            // Function to submit assignment via API
            function submitAssignment(assignmentId, fileUploadId, button) {
                // Show loading indicator
                const originalText = button.innerHTML;
                button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> জমা দেওয়া হচ্ছে...';
                button.disabled = true;
                
                // Get comments from textarea (if exists)
                const commentsTextarea = document.querySelector('textarea[name="comments"]');
                const comments = commentsTextarea ? commentsTextarea.value : '';
                
                // Prepare data for API call
                // Ensure file_upload_id is properly handled (use 0 instead of null to ensure field exists)
                const data = {
                    assignment_id: assignmentId,
                    file_upload_id: fileUploadId || 0, // Use 0 instead of null to ensure field exists
                    comments: comments
                };
                
                // Make API call to submit assignment
                fetch('api/submit_assignment.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message
                        alert('Assignment submitted successfully!');
                        
                        // Update button status
                        const row = button.closest('tr');
                        if (row && row.cells[4]) {
                            row.cells[4].innerHTML = '<span class="status-badge status-submitted">জমা দেওয়া হয়েছে</span>';
                        }
                        
                        // Change button to view results
                        button.textContent = 'ফলাফল দেখুন';
                        button.className = 'btn btn-sm btn-outline-info';
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while submitting the assignment.');
                })
                .finally(() => {
                    // Restore button
                    button.innerHTML = originalText;
                    button.disabled = false;
                });
            }
            
            // Function to delete assignment via API
            function deleteAssignment(assignmentId, button) {
                // Show loading indicator
                const originalText = button.innerHTML;
                button.innerHTML = '<i class="fas fa-spinner fa-spin me-2"></i> মুছে ফেলা হচ্ছে...';
                button.disabled = true;
                
                // Prepare data for API call
                const data = {
                    assignment_id: assignmentId
                };
                
                // Make API call to delete assignment
                fetch('api/delete_assignment.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        // Show success message
                        alert('Assignment deleted successfully!');
                        
                        // Remove the row from the table
                        const row = button.closest('tr');
                        if (row) {
                            row.remove();
                        }
                    } else {
                        alert('Error: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('An error occurred while deleting the assignment.');
                })
                .finally(() => {
                    // Restore button
                    button.innerHTML = originalText;
                    button.disabled = false;
                });
            }
        });
    </script>
</body>
</html>