<?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 {
    $stmt = $pdo->query("SELECT id, name FROM classes WHERE status = 'active' ORDER BY name");
    $classes = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    $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>
        .material-card {
            border-radius: 15px;
            overflow: hidden;
            transition: all 0.3s ease;
            margin-bottom: 20px;
            border: 1px solid #e0e0e0;
        }
        
        .material-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.1);
        }
        
        .material-header {
            background: linear-gradient(135deg, #ff758c 0%, #ff7eb3 100%);
            color: white;
            padding: 20px;
        }
        
        .material-body {
            padding: 20px;
        }
        
        .material-footer {
            background-color: #f8f9fa;
            padding: 15px 20px;
            border-top: 1px solid #e0e0e0;
        }
        
        .file-icon {
            font-size: 3rem;
            margin-bottom: 15px;
            color: #667eea;
        }
        
        .file-icon.pdf {
            color: #dc3545;
        }
        
        .file-icon.doc {
            color: #007bff;
        }
        
        .file-icon.ppt {
            color: #fd7e14;
        }
        
        .file-icon.video {
            color: #20c997;
        }
        
        .file-icon.audio {
            color: #6f42c1;
        }
        
        .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;
        }
        
        .category-filter {
            background-color: #f8f9fa;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .category-item {
            padding: 10px 15px;
            border-radius: 8px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .category-item:hover {
            background-color: #e9ecef;
        }
        
        .category-item.active {
            background-color: #667eea;
            color: white;
        }
        
        .search-box {
            position: relative;
            margin-bottom: 20px;
        }
        
        .search-box i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: #6c757d;
        }
        
        .search-box input {
            padding-left: 40px;
        }
        
        .modal-content {
            border-radius: 15px;
            overflow: hidden;
        }
        
        .student-item {
            padding: 8px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            margin-bottom: 5px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .student-item:hover {
            background-color: #f0f8ff;
            border-color: #667eea;
        }
        
        .student-item.selected {
            background-color: #e3f2fd;
            border-color: #2196f3;
        }
        
        .student-info {
            font-size: 0.9rem;
        }
        
        .student-name {
            font-weight: 500;
        }
        
        .student-details {
            color: #666;
            font-size: 0.8rem;
        }
        
        .selected-student-tag {
            display: inline-block;
            background-color: #2196f3;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            margin-right: 5px;
            margin-bottom: 5px;
        }
        
        .remove-student {
            cursor: pointer;
            margin-left: 5px;
        }
    </style>
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body>
    <div class="sidebar-container">
        <?php echo renderSidebar('online_learning/learning_materials.php', $user_role, $user_name); ?>
        
        <div class="main-content">
            <!-- Content Header -->
            <div class="content-header">
                <h1 class="content-title">
                    <i class="fas fa-book-open 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-cloud-upload-alt me-2"></i>
                                    নতুন শিক্ষা উপকরণ আপলোড
                                </h5>
                            </div>
                            <div class="card-body">
                                <form id="learningMaterialForm">
                                    <input type="hidden" id="materialId" value="">
                                    <div class="mb-3">
                                        <label class="form-label">শিরোনাম *</label>
                                        <input type="text" class="form-control" id="materialTitle" placeholder="উপকরণের শিরোনাম লিখুন" required>
                                    </div>
                                    
                                    <div class="row">
                                        <div class="col-md-6">
                                            <div class="mb-3">
                                                <label class="form-label">বিষয় *</label>
                                                <select class="form-select" id="materialSubject" 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" id="materialClass" required>
                                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?php echo $class['id']; ?>"><?php echo htmlspecialchars($class['name']); ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">বর্ণনা</label>
                                        <textarea class="form-control" id="materialDescription" rows="3" placeholder="উপকরণের বর্ণনা লিখুন"></textarea>
                                    </div>
                                    
                                    <div class="mb-3">
                                        <label class="form-label">বিভাগ *</label>
                                        <select class="form-select" id="materialCategory" required>
                                            <option value="">বিভাগ নির্বাচন করুন</option>
                                            <option value="lecture_notes">লেকচার নোট</option>
                                            <option value="presentation">প্রেজেন্টেশন</option>
                                            <option value="video_lecture">ভিডিও লেকচার</option>
                                            <option value="audio_lecture">অডিও লেকচার</option>
                                            <option value="assignment">অ্যাসাইনমেন্ট</option>
                                            <option value="practice_questions">প্রাক্টিস প্রশ্ন</option>
                                        </select>
                                    </div>
                                    
                                    <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" accept=".pdf,.doc,.docx,.ppt,.pptx,.mp4,.mp3,.jpg,.jpeg,.png">
                                        <div id="fileInfo" class="mt-2"></div>
                                        <input type="hidden" id="fileUploadId" value="">
                                    </div>
                                    
                                    <div class="alert alert-info">
                                        <i class="fas fa-info-circle me-2"></i>
                                        সমর্থিত ফাইল ফরম্যাট: PDF, DOC, DOCX, PPT, PPTX, MP4, MP3, JPG, PNG
                                    </div>
                                    
                                    <div class="mb-3">
                                        <button type="button" class="btn btn-primary" id="saveMaterialBtn">
                                            <i class="fas fa-save me-2"></i>
                                            <span id="saveButtonText">উপকরণ সংরক্ষণ করুন</span>
                                        </button>
                                        <button type="button" class="btn btn-secondary" id="resetFormBtn">
                                            <i class="fas fa-redo me-2"></i>
                                            রিসেট
                                        </button>
                                    </div>
                                </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="allowDownload" checked>
                                    <label class="form-check-label" for="allowDownload">
                                        ডাউনলোডের অনুমতি দিন
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="allowShare" checked>
                                    <label class="form-check-label" for="allowShare">
                                        শেয়ারের অনুমতি দিন
                                    </label>
                                </div>
                                
                                <div class="form-check mb-3">
                                    <input class="form-check-input" type="checkbox" id="allowPrint" checked>
                                    <label class="form-check-label" for="allowPrint">
                                        প্রিন্টের অনুমতি দিন
                                    </label>
                                </div>
                                
                                <div class="mb-3">
                                    <label class="form-label">অ্যাক্সেস নিয়ন্ত্রণ</label>
                                    <select class="form-select" id="accessControl">
                                        <option value="all">সবার জন্য</option>
                                        <option value="class_only">শুধুমাত্র ক্লাস</option>
                                        <option value="specific_students">শুধুমাত্র নির্দিষ্ট ছাত্র-ছাত্রীদের জন্য</option>
                                    </select>
                                </div>
                                
                                <!-- Specific Students Selection (Hidden by default) -->
                                <div id="specificStudentsSection" class="d-none">
                                    <div class="mb-3">
                                        <label class="form-label">ছাত্র-ছাত্রী নির্বাচন করুন</label>
                                        <!-- Search Filters -->
                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <select class="form-select" id="searchSession">
                                                    <option value="">সেশন নির্বাচন করুন</option>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <select class="form-select" id="searchClass">
                                                    <option value="">ক্লাস নির্বাচন করুন</option>
                                                    <?php foreach ($classes as $class): ?>
                                                        <option value="<?php echo $class['id']; ?>"><?php echo htmlspecialchars($class['name']); ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-4">
                                                <input type="text" class="form-control" id="searchStudent" placeholder="নাম, রোল, আইডি দ্বারা অনুসন্ধান">
                                            </div>
                                        </div>
                                        
                                        <!-- Search Button -->
                                        <button type="button" class="btn btn-primary btn-sm mb-3" id="searchStudentsBtn">
                                            <i class="fas fa-search me-1"></i> অনুসন্ধান
                                        </button>
                                        
                                        <!-- Students List -->
                                        <div id="studentsListContainer" style="max-height: 300px; overflow-y: auto; border: 1px solid #ddd; border-radius: 5px; padding: 10px;">
                                            <div class="text-center py-3" id="studentsLoading">
                                                <div class="spinner-border text-primary" role="status">
                                                    <span class="visually-hidden">লোড হচ্ছে...</span>
                                                </div>
                                                <p class="mt-2 mb-0">ছাত্র-ছাত্রীদের তালিকা লোড হচ্ছে...</p>
                                            </div>
                                            <div id="studentsList" class="d-none"></div>
                                        </div>
                                        
                                        <!-- Selected Students -->
                                        <div class="mt-3">
                                            <label class="form-label">নির্বাচিত ছাত্র-ছাত্রীরা:</label>
                                            <div id="selectedStudents" class="border rounded p-2" style="min-height: 50px;">
                                                <small class="text-muted">কোন ছাত্র-ছাত্রী নির্বাচন করা হয়নি</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                <!-- Student View -->
                <div class="search-box">
                    <i class="fas fa-search"></i>
                    <input type="text" class="form-control" id="searchInput" placeholder="শিক্ষা উপকরণ অনুসন্ধান করুন...">
                </div>
                
                <div class="category-filter">
                    <div class="row">
                        <div class="col-md-2 col-4">
                            <div class="category-item active text-center" data-category="">
                                <i class="fas fa-book fa-2x mb-2"></i>
                                <div>সব</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-4">
                            <div class="category-item text-center" data-category="lecture_notes">
                                <i class="fas fa-file-pdf fa-2x mb-2"></i>
                                <div>লেকচার নোট</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-4">
                            <div class="category-item text-center" data-category="presentation">
                                <i class="fas fa-file-powerpoint fa-2x mb-2"></i>
                                <div>প্রেজেন্টেশন</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-4">
                            <div class="category-item text-center" data-category="video_lecture">
                                <i class="fas fa-video fa-2x mb-2"></i>
                                <div>ভিডিও</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-4">
                            <div class="category-item text-center" data-category="audio_lecture">
                                <i class="fas fa-music fa-2x mb-2"></i>
                                <div>অডিও</div>
                            </div>
                        </div>
                        <div class="col-md-2 col-4">
                            <div class="category-item text-center" data-category="practice_questions">
                                <i class="fas fa-question-circle fa-2x mb-2"></i>
                                <div>প্রাক্টিস</div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
                
                <!-- Learning Materials Grid -->
                <div class="row" id="materialsContainer">
                    <!-- Materials will be loaded here via AJAX -->
                    <div class="col-12 text-center py-5">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">লোড হচ্ছে...</span>
                        </div>
                        <p class="mt-2">শিক্ষা উপকরণ লোড হচ্ছে...</p>
                    </div>
                </div>
                
                <!-- Pagination -->
                <nav aria-label="Page navigation" class="mt-4 d-none" id="paginationContainer">
                    <ul class="pagination justify-content-center" id="pagination">
                    </ul>
                </nav>
            </div>
        </div>
    </div>

    <!-- Delete Confirmation Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header bg-danger text-white">
                    <h5 class="modal-title" id="deleteModalLabel">নিশ্চিতকরণ</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>আপনি কি নিশ্চিত যে আপনি এই শিক্ষা উপকরণটি মুছে ফেলতে চান? এই ক্রিয়াটি পূর্বাবস্থায় ফেরানো যাবে না।</p>
                    <input type="hidden" id="deleteMaterialId">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">মুছে ফেলুন</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Global variables
        let currentCategory = '';
        let currentSearch = '';
        let fileUploadId = null;
        
        // DOM Ready
        document.addEventListener('DOMContentLoaded', function() {
            // Load materials on page load
            loadMaterials();
            
            // Load sessions for dropdown
            loadSessions();
            
            // Category filter functionality
            const categoryItems = document.querySelectorAll('.category-item');
            categoryItems.forEach(item => {
                item.addEventListener('click', function() {
                    // Remove active class from all items
                    categoryItems.forEach(i => i.classList.remove('active'));
                    // Add active class to clicked item
                    this.classList.add('active');
                    // Set current category
                    currentCategory = this.getAttribute('data-category');
                    // Load materials with new filter
                    loadMaterials();
                });
            });
            
            // Search functionality
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                searchInput.addEventListener('input', function() {
                    currentSearch = this.value;
                    loadMaterials();
                });
            }
            
            // File upload functionality
            const uploadArea = document.getElementById('uploadArea');
            const fileInput = document.getElementById('fileInput');
            
            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) {
                    handleFileUpload(e.dataTransfer.files[0]);
                }
            });
            
            fileInput.addEventListener('change', function() {
                if (this.files.length) {
                    handleFileUpload(this.files[0]);
                }
            });
            
            // Save material button
            document.getElementById('saveMaterialBtn').addEventListener('click', saveMaterial);
            
            // Reset form button
            document.getElementById('resetFormBtn').addEventListener('click', resetForm);
            
            // Confirm delete button
            document.getElementById('confirmDeleteBtn').addEventListener('click', deleteMaterial);
            
            // Access control change event
            document.getElementById('accessControl').addEventListener('change', toggleSpecificStudentsSection);
            
            // Search students button
            document.getElementById('searchStudentsBtn').addEventListener('click', loadStudents);
            
            // Search student input (enter key)
            document.getElementById('searchStudent').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    loadStudents();
                }
            });
        });
        
        // Handle file upload
        function handleFileUpload(file) {
            // Show uploading status
            const fileInfo = document.getElementById('fileInfo');
            fileInfo.innerHTML = `
                <div class="alert alert-info">
                    <i class="fas fa-spinner fa-spin me-2"></i>
                    ফাইল আপলোড হচ্ছে...
                </div>
            `;
            
            // Create FormData object
            const formData = new FormData();
            formData.append('learning_material', file);
            
            // Upload file to server
            fetch('api/upload_assignment_file.php', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Store the uploaded file ID
                    fileUploadId = data.file_upload_id;
                    document.getElementById('fileUploadId').value = data.file_upload_id;
                    
                    // Show success status
                    fileInfo.innerHTML = `
                        <div class="alert alert-success">
                            <i class="fas fa-check-circle me-2"></i>
                            ${file.name} (${(file.size/1024).toFixed(1)} KB)
                        </div>
                    `;
                } else {
                    // Show error status
                    fileInfo.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-circle me-2"></i>
                            ত্রুটি: ${data.message}
                        </div>
                    `;
                    fileUploadId = null;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                // Show error status
                fileInfo.innerHTML = `
                    <div class="alert alert-danger">
                        <i class="fas fa-exclamation-circle me-2"></i>
                        ফাইল আপলোডে ত্রুটি হয়েছে
                    </div>
                `;
                fileUploadId = null;
            });
        }
        
        // Load sessions for dropdown
        function loadSessions() {
            fetch('api/get_sessions.php')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const sessionSelect = document.getElementById('searchSession');
                        sessionSelect.innerHTML = '<option value="">সেশন নির্বাচন করুন</option>';
                        
                        data.sessions.forEach(session => {
                            const option = document.createElement('option');
                            option.value = session.id;
                            option.textContent = session.session_name;
                            sessionSelect.appendChild(option);
                        });
                    }
                })
                .catch(error => {
                    console.error('Error loading sessions:', error);
                });
        }
        
        // Load materials via AJAX
        function loadMaterials() {
            // Show loading indicator
            document.getElementById('materialsContainer').innerHTML = `
                <div class="col-12 text-center py-5">
                    <div class="spinner-border text-primary" role="status">
                        <span class="visually-hidden">লোড হচ্ছে...</span>
                    </div>
                    <p class="mt-2">শিক্ষা উপকরণ লোড হচ্ছে...</p>
                </div>
            `;
            
            // Build query parameters
            const params = new URLSearchParams();
            if (currentCategory) params.append('category', currentCategory);
            if (currentSearch) params.append('search', currentSearch);
            
            // Fetch materials
            fetch(`api/get_learning_materials.php?${params.toString()}`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    displayMaterials(data.materials);
                } else {
                    document.getElementById('materialsContainer').innerHTML = `
                        <div class="col-12 text-center py-5">
                            <i class="fas fa-exclamation-circle fa-3x text-danger mb-3"></i>
                            <h4>ত্রুটি</h4>
                            <p>${data.message}</p>
                        </div>
                    `;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                document.getElementById('materialsContainer').innerHTML = `
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-exclamation-circle fa-3x text-danger mb-3"></i>
                        <h4>ত্রুটি</h4>
                        <p>শিক্ষা উপকরণ লোড করতে সমস্যা হয়েছে</p>
                    </div>
                `;
            });
        }
        
        // Display materials in grid
        function displayMaterials(materials) {
            const container = document.getElementById('materialsContainer');
            
            if (materials.length === 0) {
                container.innerHTML = `
                    <div class="col-12 text-center py-5">
                        <i class="fas fa-book-open fa-3x text-muted mb-3"></i>
                        <h4>কোন শিক্ষা উপকরণ পাওয়া যায়নি</h4>
                        <p class="text-muted">পরবর্তীতে আরও উপকরণ যুক্ত হবে</p>
                    </div>
                `;
                return;
            }
            
            let html = '';
            materials.forEach(material => {
                html += `
                    <div class="col-lg-4 col-md-6">
                        <div class="material-card">
                            <div class="material-header">
                                <h5>${material.title}</h5>
                                <p class="mb-0">${material.category_display}</p>
                            </div>
                            <div class="material-body text-center">
                                <div class="file-icon ${getFileIconClass(material.file_type)}">
                                    <i class="${material.icon_class}"></i>
                                </div>
                                <p>${material.description || 'কোন বর্ণনা নেই'}</p>
                                <div class="text-muted">
                                    <small>
                                        <i class="fas fa-user me-1"></i> ${material.created_by}
                                        <i class="fas fa-calendar ms-2 me-1"></i> ${formatDate(material.created_at)}
                                    </small>
                                </div>
                            </div>
                            <div class="material-footer">
                                <div class="d-flex justify-content-between">
                                    <span>
                                        ${material.download_count > 0 ? 
                                            `<i class="fas fa-download me-1"></i> ${material.download_count} ডাউনলোড` : 
                                            `<i class="fas fa-eye me-1"></i> ${material.view_count} ভিউ`}
                                    </span>
                                    <div>
                                        ${<?php echo json_encode($user_role == 'admin' || $user_role == 'teacher'); ?> ? 
                                            `
                                            <button class="btn btn-sm btn-outline-primary edit-btn" data-id="${material.id}">
                                                <i class="fas fa-edit"></i>
                                            </button>
                                            <button class="btn btn-sm btn-outline-danger delete-btn" data-id="${material.id}">
                                                <i class="fas fa-trash"></i>
                                            </button>
                                            ` : 
                                            `
                                            ${material.allow_download ? 
                                                `<button class="btn btn-sm btn-primary download-btn" data-id="${material.id}">
                                                    <i class="fas fa-download me-1"></i> ডাউনলোড
                                                </button>` :
                                                `<button class="btn btn-sm btn-primary view-btn" data-id="${material.id}">
                                                    <i class="fas fa-eye me-1"></i> দেখুন
                                                </button>`}
                                            `}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
            
            // Add event listeners to buttons
            if (<?php echo json_encode($user_role == 'admin' || $user_role == 'teacher'); ?>) {
                document.querySelectorAll('.edit-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        editMaterial(this.getAttribute('data-id'));
                    });
                });
                
                document.querySelectorAll('.delete-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        document.getElementById('deleteMaterialId').value = this.getAttribute('data-id');
                        new bootstrap.Modal(document.getElementById('deleteModal')).show();
                    });
                });
            } else {
                document.querySelectorAll('.download-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        accessMaterial(this.getAttribute('data-id'), 'download');
                    });
                });
                
                document.querySelectorAll('.view-btn').forEach(btn => {
                    btn.addEventListener('click', function() {
                        accessMaterial(this.getAttribute('data-id'), 'view');
                    });
                });
            }
        }
        
        // Get file icon class based on file type
        function getFileIconClass(fileType) {
            fileType = fileType.toLowerCase();
            if (fileType.includes('pdf')) return 'pdf';
            if (fileType.includes('word') || fileType.includes('doc')) return 'doc';
            if (fileType.includes('powerpoint') || fileType.includes('ppt')) return 'ppt';
            if (fileType.includes('video')) return 'video';
            if (fileType.includes('audio')) return 'audio';
            return '';
        }
        
        // Format date for display
        function formatDate(dateString) {
            const date = new Date(dateString);
            const options = { day: 'numeric', month: 'short', year: 'numeric' };
            return date.toLocaleDateString('bn-BD', options);
        }
        
        // Save material
        function saveMaterial() {
            // Get form data
            const materialId = document.getElementById('materialId').value;
            const title = document.getElementById('materialTitle').value.trim();
            const description = document.getElementById('materialDescription').value.trim();
            const classId = document.getElementById('materialClass').value;
            const subjectId = document.getElementById('materialSubject').value;
            const category = document.getElementById('materialCategory').value;
            const fileUploadId = document.getElementById('fileUploadId').value;
            
            // Validate required fields
            if (!title || !classId || !subjectId || !category || !fileUploadId) {
                alert('দয়া করে সব প্রয়োজনীয় তথ্য পূরণ করুন');
                return;
            }
            
            // Get settings
            const allowDownload = document.getElementById('allowDownload').checked ? 1 : 0;
            const allowShare = document.getElementById('allowShare').checked ? 1 : 0;
            const allowPrint = document.getElementById('allowPrint').checked ? 1 : 0;
            const accessControl = document.getElementById('accessControl').value;
            
            // Get selected student IDs if access control is specific_students
            let specificStudentIds = [];
            if (accessControl === 'specific_students') {
                specificStudentIds = getSelectedStudentIds();
                
                // Validate that at least one student is selected
                if (specificStudentIds.length === 0) {
                    alert('দয়া করে অন্তত একজন ছাত্র-ছাত্রী নির্বাচন করুন');
                    return;
                }
            }
            
            // Prepare data
            const data = {
                title: title,
                description: description,
                class_id: parseInt(classId),
                subject_id: parseInt(subjectId),
                category: category,
                file_upload_id: parseInt(fileUploadId),
                allow_download: allowDownload,
                allow_share: allowShare,
                allow_print: allowPrint,
                access_control: accessControl
            };
            
            // Add specific student IDs if access control is specific_students
            if (accessControl === 'specific_students') {
                data.specific_student_ids = specificStudentIds;
            }
            
            // Add ID for edit operation
            if (materialId) {
                data.id = parseInt(materialId);
            }
            
            // Disable save button
            const saveBtn = document.getElementById('saveMaterialBtn');
            const saveBtnText = document.getElementById('saveButtonText');
            const originalText = saveBtnText.textContent;
            saveBtnText.textContent = 'সংরক্ষণ হচ্ছে...';
            saveBtn.disabled = true;
            
            // Send data to API
            const apiUrl = materialId ? 'api/edit_learning_material.php' : 'api/add_learning_material.php';
            
            fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('শিক্ষা উপকরণ সফলভাবে সংরক্ষিত হয়েছে');
                    resetForm();
                    loadMaterials();
                } else {
                    alert('ত্রুটি: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('শিক্ষা উপকরণ সংরক্ষণে ত্রুটি হয়েছে');
            })
            .finally(() => {
                // Re-enable save button
                saveBtnText.textContent = originalText;
                saveBtn.disabled = false;
            });
        }
        
        // Edit material
        function editMaterial(materialId) {
            // In a real implementation, you would fetch the material details and populate the form
            alert('Edit functionality would be implemented here for material ID: ' + materialId);
            // TODO: Fetch material details and populate form
            // TODO: If access_control is specific_students, load and select the specific students
        }
        
        // Delete material
        function deleteMaterial() {
            const materialId = document.getElementById('deleteMaterialId').value;
            
            // Send delete request
            fetch('api/delete_learning_material.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ id: parseInt(materialId) })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('শিক্ষা উপকরণ সফলভাবে মুছে ফেলা হয়েছে');
                    // Hide modal
                    bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                    // Reload materials
                    loadMaterials();
                } else {
                    alert('ত্রুটি: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('শিক্ষা উপকরণ মুছে ফেলতে ত্রুটি হয়েছে');
            });
        }
        
        // Access material (view/download)
        function accessMaterial(materialId, action) {
            // Send access request
            fetch('api/access_learning_material.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ 
                    id: parseInt(materialId),
                    action: action
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Redirect to download URL
                    if (data.download_url) {
                        window.open(data.download_url, '_blank');
                    } else if (data.view_url) {
                        window.open(data.view_url, '_blank');
                    }
                } else {
                    alert('ত্রুটি: ' + data.message);
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('উপকরণ অ্যাক্সেস করতে ত্রুটি হয়েছে');
            });
        }
        
        // Reset form
        function resetForm() {
            document.getElementById('learningMaterialForm').reset();
            document.getElementById('materialId').value = '';
            document.getElementById('fileUploadId').value = '';
            document.getElementById('fileInfo').innerHTML = '';
            document.getElementById('saveButtonText').textContent = 'উপকরণ সংরক্ষণ করুন';
            fileUploadId = null;
            
            // Reset specific students section
            document.getElementById('specificStudentsSection').classList.add('d-none');
            document.getElementById('selectedStudents').innerHTML = '<small class="text-muted">কোন ছাত্র-ছাত্রী নির্বাচন করা হয়নি</small>';
        }
        
        // Toggle specific students section based on access control
        function toggleSpecificStudentsSection() {
            const accessControl = document.getElementById('accessControl').value;
            const specificStudentsSection = document.getElementById('specificStudentsSection');
            
            if (accessControl === 'specific_students') {
                specificStudentsSection.classList.remove('d-none');
                loadStudents(); // Load students when section is shown
            } else {
                specificStudentsSection.classList.add('d-none');
            }
        }
        
        // Load students based on filters
        function loadStudents() {
            const session = document.getElementById('searchSession').value;
            const classId = document.getElementById('searchClass').value;
            const search = document.getElementById('searchStudent').value;
            
            // Show loading indicator
            document.getElementById('studentsLoading').classList.remove('d-none');
            document.getElementById('studentsList').classList.add('d-none');
            
            // Build query parameters
            const params = new URLSearchParams();
            if (session) params.append('session', session);
            if (classId) params.append('class_id', classId);
            if (search) params.append('search', search);
            
            // Fetch students
            fetch(`api/get_students.php?${params.toString()}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        displayStudents(data.students);
                    } else {
                        document.getElementById('studentsList').innerHTML = `
                            <div class="text-center text-danger">
                                <i class="fas fa-exclamation-circle"></i>
                                <p>ত্রুটি: ${data.message}</p>
                            </div>
                        `;
                        document.getElementById('studentsList').classList.remove('d-none');
                    }
                    document.getElementById('studentsLoading').classList.add('d-none');
                })
                .catch(error => {
                    console.error('Error:', error);
                    document.getElementById('studentsList').innerHTML = `
                        <div class="text-center text-danger">
                            <i class="fas fa-exclamation-circle"></i>
                            <p>ছাত্র-ছাত্রীদের তালিকা লোড করতে ত্রুটি হয়েছে</p>
                        </div>
                    `;
                    document.getElementById('studentsList').classList.remove('d-none');
                    document.getElementById('studentsLoading').classList.add('d-none');
                });
        }
        
        // Display students in the list
        function displayStudents(students) {
            const container = document.getElementById('studentsList');
            
            if (students.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-muted">
                        <i class="fas fa-user-graduate fa-2x mb-2"></i>
                        <p>কোন ছাত্র-ছাত্রী পাওয়া যায়নি</p>
                    </div>
                `;
            } else {
                let html = '';
                students.forEach(student => {
                    html += `
                        <div class="student-item" data-id="${student.id}" data-name="${student.first_name} ${student.last_name}">
                            <div class="student-info">
                                <div class="student-name">${student.first_name} ${student.last_name}</div>
                                <div class="student-details">
                                    ক্লাস: ${student.class_name} | রোল: ${student.roll_number || 'N/A'} | আইডি: ${student.student_id}
                                </div>
                            </div>
                        </div>
                    `;
                });
                container.innerHTML = html;
                
                // Add click event to student items
                document.querySelectorAll('.student-item').forEach(item => {
                    item.addEventListener('click', function() {
                        this.classList.toggle('selected');
                        updateSelectedStudents();
                    });
                });
            }
            
            container.classList.remove('d-none');
        }
        
        // Update selected students display
        function updateSelectedStudents() {
            const selectedStudentsContainer = document.getElementById('selectedStudents');
            const selectedItems = document.querySelectorAll('.student-item.selected');
            
            if (selectedItems.length === 0) {
                selectedStudentsContainer.innerHTML = '<small class="text-muted">কোন ছাত্র-ছাত্রী নির্বাচন করা হয়নি</small>';
                return;
            }
            
            let html = '';
            selectedItems.forEach(item => {
                const id = item.getAttribute('data-id');
                const name = item.getAttribute('data-name');
                html += `
                    <span class="selected-student-tag" data-id="${id}">
                        ${name}
                        <span class="remove-student" data-id="${id}">✕</span>
                    </span>
                `;
            });
            
            selectedStudentsContainer.innerHTML = html;
            
            // Add click event to remove buttons
            document.querySelectorAll('.remove-student').forEach(btn => {
                btn.addEventListener('click', function(e) {
                    e.stopPropagation();
                    const id = this.getAttribute('data-id');
                    // Remove from selected list
                    const tag = this.parentElement;
                    tag.remove();
                    // Unselect from list
                    const studentItem = document.querySelector(`.student-item[data-id="${id}"]`);
                    if (studentItem) {
                        studentItem.classList.remove('selected');
                    }
                    // Update if no students left
                    if (document.querySelectorAll('.selected-student-tag').length === 0) {
                        selectedStudentsContainer.innerHTML = '<small class="text-muted">কোন ছাত্র-ছাত্রী নির্বাচন করা হয়নি</small>';
                    }
                });
            });
        }
        
        // Get selected student IDs
        function getSelectedStudentIds() {
            const selectedItems = document.querySelectorAll('.student-item.selected');
            const ids = [];
            selectedItems.forEach(item => {
                ids.push(parseInt(item.getAttribute('data-id')));
            });
            return ids;
        }
    </script>
</body>
</html>