<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
require_once '../includes/functions.php';
require_once '../includes/middleware.php';

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$db = getDB();
$userId = $_SESSION['user_id'];

// Handle file uploads
$message = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'upload_resource':
                $courseId = !empty($_POST['course_id']) ? $_POST['course_id'] : null;
                $moduleId = !empty($_POST['module_id']) ? $_POST['module_id'] : null;
                $lessonId = !empty($_POST['lesson_id']) ? $_POST['lesson_id'] : null;
                $title = trim($_POST['title']);
                $description = trim($_POST['description']);
                $category = trim($_POST['category']);
                $tags = array_filter(array_map('trim', explode(',', $_POST['tags'] ?? '')));
                $isShared = isset($_POST['is_shared']);
                $sharingPermissions = isset($_POST['sharing_permissions']) ? $_POST['sharing_permissions'] : ['instructor'];

                if (empty($title)) {
                    $error = 'Resource title is required.';
                } else {
                    try {
                        $resourceType = 'other';
                        $filePath = null;
                        $fileName = null;
                        $fileSize = 0;
                        $mimeType = null;
                        $externalUrl = null;

                        // Handle file upload
                        if (isset($_FILES['resource_file']) && $_FILES['resource_file']['error'] === UPLOAD_ERR_OK) {
                            $uploadDir = '../uploads/resources/';
                            if (!is_dir($uploadDir)) mkdir($uploadDir, 0755, true);

                            $originalName = basename($_FILES['resource_file']['name']);
                            $fileExtension = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
                            $fileName = time() . '_' . uniqid() . '.' . $fileExtension;
                            $targetPath = $uploadDir . $fileName;

                            // Determine resource type based on file extension
                            $resourceType = getResourceTypeFromExtension($fileExtension);

                            // Validate file type and size
                            if (!validateResourceFile($fileExtension, $_FILES['resource_file']['size'])) {
                                $error = 'Invalid file type or file too large.';
                                break;
                            }

                            if (move_uploaded_file($_FILES['resource_file']['tmp_name'], $targetPath)) {
                                $filePath = 'uploads/resources/' . $fileName;
                                $fileSize = $_FILES['resource_file']['size'];
                                $mimeType = $_FILES['resource_file']['type'];
                            } else {
                                $error = 'Failed to upload file.';
                                break;
                            }
                        } elseif (!empty($_POST['external_url'])) {
                            $externalUrl = trim($_POST['external_url']);
                            $resourceType = 'link';
                        } else {
                            $error = 'Please upload a file or provide an external URL.';
                            break;
                        }

                        // Generate slug
                        $slug = createSlug($title);
                        $originalSlug = $slug;
                        $counter = 1;
                        while (true) {
                            $stmt = $db->prepare("SELECT id FROM course_resources WHERE course_id = ? AND slug = ?");
                            $stmt->execute([$courseId, $slug]);
                            if (!$stmt->fetch()) break;
                            $slug = $originalSlug . '-' . $counter;
                            $counter++;
                        }

                        // Insert resource
                        $stmt = $db->prepare("INSERT INTO course_resources (course_id, module_id, lesson_id, title, slug, description, resource_type, file_path, file_name, file_size, mime_type, external_url, category, tags, is_shared, sharing_permissions, created_by, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())");

                        $stmt->execute([
                            $courseId, $moduleId, $lessonId, $title, $slug, $description, $resourceType,
                            $filePath, $fileName, $fileSize, $mimeType, $externalUrl, $category,
                            json_encode($tags), $isShared, json_encode($sharingPermissions), $userId
                        ]);

                        $message = 'Resource uploaded successfully.';

                    } catch (PDOException $e) {
                        $error = 'Error uploading resource: ' . $e->getMessage();
                    }
                }
                break;

            case 'delete_resource':
                $resourceId = $_POST['resource_id'];

                try {
                    // Get resource info for file deletion
                    $stmt = $db->prepare("SELECT file_path FROM course_resources WHERE id = ? AND created_by = ?");
                    $stmt->execute([$resourceId, $userId]);
                    $resource = $stmt->fetch();

                    if ($resource) {
                        // Delete physical file if exists
                        if ($resource['file_path'] && file_exists('../' . $resource['file_path'])) {
                            unlink('../' . $resource['file_path']);
                        }

                        // Delete from database
                        $stmt = $db->prepare("DELETE FROM course_resources WHERE id = ? AND created_by = ?");
                        $stmt->execute([$resourceId, $userId]);

                        $message = 'Resource deleted successfully.';
                    } else {
                        $error = 'Resource not found or access denied.';
                    }

                } catch (PDOException $e) {
                    $error = 'Error deleting resource: ' . $e->getMessage();
                }
                break;

            case 'bulk_delete':
                $resourceIds = $_POST['resource_ids'] ?? [];

                if (empty($resourceIds)) {
                    $error = 'No resources selected.';
                } else {
                    try {
                        $placeholders = str_repeat('?,', count($resourceIds) - 1) . '?';
                        $stmt = $db->prepare("SELECT id, file_path FROM course_resources WHERE id IN ($placeholders) AND created_by = ?");
                        $stmt->execute(array_merge($resourceIds, [$userId]));
                        $resources = $stmt->fetchAll();

                        if (count($resources) === count($resourceIds)) {
                            // Delete physical files
                            foreach ($resources as $resource) {
                                if ($resource['file_path'] && file_exists('../' . $resource['file_path'])) {
                                    unlink('../' . $resource['file_path']);
                                }
                            }

                            // Delete from database
                            $stmt = $db->prepare("DELETE FROM course_resources WHERE id IN ($placeholders) AND created_by = ?");
                            $stmt->execute(array_merge($resourceIds, [$userId]));

                            $message = count($resourceIds) . ' resources deleted successfully.';
                        } else {
                            $error = 'Some resources not found or access denied.';
                        }

                    } catch (PDOException $e) {
                        $error = 'Error deleting resources: ' . $e->getMessage();
                    }
                }
                break;
        }
    }
}

// Get filter parameters
$courseId = $_GET['course_id'] ?? null;
$category = $_GET['category'] ?? null;
$resourceType = $_GET['type'] ?? null;
$search = $_GET['search'] ?? null;

// Build query for resources
$query = "
    SELECT cr.*, c.title as course_title, cm.title as module_title, cl.title as lesson_title,
           u.username as creator_name
    FROM course_resources cr
    LEFT JOIN courses c ON cr.course_id = c.id
    LEFT JOIN course_modules cm ON cr.module_id = cm.id
    LEFT JOIN course_lessons cl ON cr.lesson_id = cl.id
    LEFT JOIN users u ON cr.created_by = u.id
    WHERE cr.created_by = ?
";

$params = [$userId];

if ($courseId) {
    $query .= " AND cr.course_id = ?";
    $params[] = $courseId;
}

if ($category) {
    $query .= " AND cr.category = ?";
    $params[] = $category;
}

if ($resourceType) {
    $query .= " AND cr.resource_type = ?";
    $params[] = $resourceType;
}

if ($search) {
    $query .= " AND (cr.title LIKE ? OR cr.description LIKE ? OR cr.tags LIKE ?)";
    $searchTerm = "%$search%";
    $params[] = $searchTerm;
    $params[] = $searchTerm;
    $params[] = $searchTerm;
}

$query .= " ORDER BY cr.created_at DESC";

$stmt = $db->prepare($query);
$stmt->execute($params);
$resources = $stmt->fetchAll();

// Get courses for filter dropdown
$stmt = $db->prepare("SELECT id, title FROM courses WHERE instructor_id = ? ORDER BY title");
$stmt->execute([$userId]);
$courses = $stmt->fetchAll();

// Get categories for filter
$stmt = $db->query("SELECT DISTINCT category FROM course_resources WHERE category IS NOT NULL AND category != '' ORDER BY category");
$categories = $stmt->fetchAll(PDO::FETCH_COLUMN);

$pageTitle = 'Resource Library - Mutalex Academy';
?>

<script src="https://cdn.tailwindcss.com"></script>
<style>
    @import url('https://fonts.googleapis.com/css2?family=Inter:wght@100..900&display=swap');
    body {
        font-family: 'Inter', sans-serif;
        background-color: #f7f9fb;
    }
    /* Custom scrollbar for better aesthetics */
    ::-webkit-scrollbar { width: 8px; }
    ::-webkit-scrollbar-track { background: #f1f1f1; }
    ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 4px; }
    ::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
    .resource-card {
        transition: transform 0.2s, box-shadow 0.2s;
    }
    .resource-card:hover {
        transform: translateY(-4px);
        box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
    }
    .tag {
        cursor: pointer;
        transition: background-color 0.1s;
    }
    .tag:hover {
        background-color: #e0f2f1;
    }
    .modal-overlay {
        background-color: rgba(0, 0, 0, 0.6);
    }
</style>

<!-- Main Application Container -->
<div class="p-4 sm:p-8">
        <!-- Header -->
        <header class="mb-8 flex flex-col sm:flex-row justify-between items-start sm:items-center">
            <h1 class="text-3xl font-bold text-gray-800 mb-2 sm:mb-0">
                Study Resource Library
            </h1>
            <button id="open-upload-modal" class="flex items-center space-x-2 bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out transform hover:scale-[1.02]">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 5v14"/><path d="M5 12h14"/></svg>
                <span>Upload New Resource</span>
            </button>
        </header>

        <!-- Alerts -->
        <?php if ($message): ?>
            <div class="alert alert-success alert-dismissible fade show mb-4" role="alert" style="border-radius: 0.75rem; border: none; background: linear-gradient(135deg, #dcfce7 0%, #bbf7d0 100%); color: #166534; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                <i class="fas fa-check-circle me-2"></i><?php echo htmlspecialchars($message); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if ($error): ?>
            <div class="alert alert-danger alert-dismissible fade show mb-4" role="alert" style="border-radius: 0.75rem; border: none; background: linear-gradient(135deg, #fef2f2 0%, #fecaca 100%); color: #dc2626; box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);">
                <i class="fas fa-exclamation-triangle me-2"></i><?php echo htmlspecialchars($error); ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Search and Filter Bar -->
        <div class="bg-white p-6 rounded-xl shadow-lg mb-8 border border-gray-100">
            <h2 class="text-xl font-semibold text-gray-700 mb-4">Filter Resources</h2>
            <form method="GET" class="grid grid-cols-1 md:grid-cols-4 gap-4">
                <!-- Search Input -->
                <div>
                    <label for="search" class="block text-sm font-medium text-gray-700 mb-1">Search Title / Tag</label>
                    <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search ?? ''); ?>" placeholder="e.g., React, SQL, Midterm" class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                </div>

                <!-- Category Filter -->
                <div>
                    <label for="category-filter" class="block text-sm font-medium text-gray-700 mb-1">Category</label>
                    <select id="category-filter" name="category" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                        <option value="">All Categories</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo htmlspecialchars($cat); ?>" <?php echo $category === $cat ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($cat); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Course Filter -->
                <div>
                    <label for="course-filter" class="block text-sm font-medium text-gray-700 mb-1">Course</label>
                    <select id="course-filter" name="course_id" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                        <option value="">All Courses</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo $course['id']; ?>" <?php echo $courseId == $course['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($course['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Type Filter -->
                <div>
                    <label for="type-filter" class="block text-sm font-medium text-gray-700 mb-1">Resource Type</label>
                    <select id="type-filter" name="type" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500 transition duration-150">
                        <option value="">All Types</option>
                        <option value="document" <?php echo $resourceType === 'document' ? 'selected' : ''; ?>>Document</option>
                        <option value="audio" <?php echo $resourceType === 'audio' ? 'selected' : ''; ?>>Audio</option>
                        <option value="image" <?php echo $resourceType === 'image' ? 'selected' : ''; ?>>Image</option>
                        <option value="link" <?php echo $resourceType === 'link' ? 'selected' : ''; ?>>Link</option>
                        <option value="archive" <?php echo $resourceType === 'archive' ? 'selected' : ''; ?>>Archive</option>
                        <option value="other" <?php echo $resourceType === 'other' ? 'selected' : ''; ?>>Other</option>
                    </select>
                </div>
            </form>
        </div>

        <!-- Resource Grid -->
        <div id="resource-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
            <?php if (empty($resources)): ?>
                <!-- No Results Message -->
                <div class="col-span-full text-center py-12">
                    <p class="text-xl text-gray-500">No resources matched your current filter criteria. Try adjusting your search terms.</p>
                </div>
            <?php else: ?>
                <?php foreach ($resources as $resource): ?>
                    <div class="resource-card bg-white rounded-xl p-6 shadow-md border border-gray-100 flex flex-col justify-between">
                        <div>
                            <div class="flex items-center space-x-3 mb-3">
                                <?php
                                $iconSvg = match($resource['resource_type']) {
                                    'document' => '<path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><path d="M14 2v6h6"/><path d="M16 13H8"/><path d="M16 17H8"/><path d="M10 9H8"/>',
                                    'audio' => '<path d="M3 10v4h2l3 3V7l-3 3H3z"/><path d="M16.14 8.13a4.95 4.95 0 0 1 0 7.74"/><path d="M19.78 5.57a9.4 9.4 0 0 1 0 12.86"/>',
                                    'image' => '<rect width="18" height="18" x="3" y="3" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',
                                    'archive' => '<rect width="20" height="5" x="2" y="3" rx="1"/><path d="M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8"/><path d="M10 12h4"/>',
                                    default => '<circle cx="12" cy="12" r="10"/><path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/><path d="M12 17h.01"/>'
                                };
                                $colorClass = match($resource['resource_type']) {
                                    'document' => 'text-indigo-500',
                                    'audio' => 'text-green-500',
                                    'image' => 'text-red-500',
                                    'archive' => 'text-yellow-600',
                                    default => 'text-gray-500'
                                };
                                ?>
                                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="w-8 h-8 flex-shrink-0 <?php echo $colorClass; ?>"><?php echo $iconSvg; ?></svg>
                                <div>
                                    <h3 class="text-lg font-bold text-gray-900 line-clamp-2"><?php echo htmlspecialchars($resource['title']); ?></h3>
                                    <p class="text-sm text-indigo-600 font-semibold"><?php echo htmlspecialchars($resource['course_title'] ?? $resource['courseId']); ?></p>
                                </div>
                            </div>

                            <p class="text-sm text-gray-500 mb-3 line-clamp-3"><?php echo htmlspecialchars($resource['description'] ?? 'No description available.'); ?></p>

                            <div class="flex flex-wrap gap-2 mb-4">
                                <?php
                                $tags = json_decode($resource['tags'] ?? '[]', true);
                                if (!empty($tags)) {
                                    foreach ($tags as $tag) {
                                        echo '<span class="tag bg-teal-50 text-teal-700 text-xs font-medium px-2 py-0.5 rounded-full hover:bg-teal-100 transition duration-150" data-tag="' . htmlspecialchars($tag) . '">#' . htmlspecialchars($tag) . '</span>';
                                    }
                                }
                                ?>
                            </div>
                        </div>

                        <div class="pt-3 border-t border-gray-100 flex justify-between items-center text-xs text-gray-400">
                            <span class="truncate pr-2" title="<?php echo htmlspecialchars($resource['creator_name']); ?>"><?php echo htmlspecialchars($resource['creator_name']); ?></span>
                            <span><?php echo date('M j, Y', strtotime($resource['created_at'])); ?></span>
                        </div>

                        <?php if ($resource['resource_type'] === 'link' && $resource['external_url']): ?>
                            <a href="<?php echo htmlspecialchars($resource['external_url']); ?>" target="_blank" class="mt-4 block text-center bg-gray-100 text-gray-700 hover:bg-indigo-100 hover:text-indigo-600 font-medium py-2 rounded-lg transition duration-150 ease-in-out">
                                View/Download
                            </a>
                        <?php elseif ($resource['file_path']): ?>
                            <a href="../<?php echo htmlspecialchars($resource['file_path']); ?>" target="_blank" class="mt-4 block text-center bg-gray-100 text-gray-700 hover:bg-indigo-100 hover:text-indigo-600 font-medium py-2 rounded-lg transition duration-150 ease-in-out">
                                View/Download
                            </a>
                        <?php endif; ?>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
        </div>
    </div>
</div>

<!-- Upload Resource Modal (Hidden by default) -->
<div id="upload-modal" class="fixed inset-0 z-50 overflow-y-auto hidden">
    <div class="modal-overlay absolute w-full h-full"></div>
    <div class="flex items-center justify-center min-h-screen p-4 sm:p-0">
        <div class="bg-white w-full max-w-2xl rounded-xl shadow-2xl z-50 overflow-hidden transform transition-all">

            <!-- Modal Header -->
            <div class="p-6 border-b border-gray-200 flex justify-between items-center">
                <h3 class="text-2xl font-bold text-gray-800">Upload New Study Resource</h3>
                <button id="close-upload-modal" class="text-gray-400 hover:text-gray-600 transition">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-6 h-6" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>
                </button>
            </div>

            <!-- Modal Body (Form) -->
            <form method="POST" enctype="multipart/form-data" class="p-6 space-y-4">
                <input type="hidden" name="action" value="upload_resource">

                <div>
                    <label for="upload-title" class="block text-sm font-medium text-gray-700 mb-1">Title <span class="text-red-500">*</span></label>
                    <input type="text" id="upload-title" name="title" required class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500">
                </div>

                <div>
                    <label for="upload-description" class="block text-sm font-medium text-gray-700 mb-1">Description</label>
                    <textarea id="upload-description" name="description" rows="3" class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500"></textarea>
                </div>

                <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                        <label for="upload-course" class="block text-sm font-medium text-gray-700 mb-1">Associated Course</label>
                        <select id="upload-course" name="course_id" class="w-full border border-gray-300 rounded-lg p-2 bg-white focus:ring-indigo-500 focus:border-indigo-500">
                            <option value="">(Optional)</option>
                            <?php foreach ($courses as $course): ?>
                                <option value="<?php echo $course['id']; ?>"><?php echo htmlspecialchars($course['title']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <label for="upload-category" class="block text-sm font-medium text-gray-700 mb-1">Category <span class="text-red-500">*</span></label>
                        <input type="text" id="upload-category" name="category" required class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500" placeholder="e.g., Notes, Solutions, Lectures">
                    </div>
                </div>

                <div>
                    <label for="upload-tags" class="block text-sm font-medium text-gray-700 mb-1">Tags (Comma-separated)</label>
                    <input type="text" id="upload-tags" name="tags" class="w-full border border-gray-300 rounded-lg p-2 focus:ring-indigo-500 focus:border-indigo-500" placeholder="e.g., Python, Data Structures, Exam Review">
                </div>

                <div>
                    <label for="upload-file" class="block text-sm font-medium text-gray-700 mb-1">Resource File <span class="text-red-500">*</span></label>
                    <input type="file" id="upload-file" name="resource_file" required class="w-full file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-sm file:font-semibold file:bg-indigo-50 file:text-indigo-700 hover:file:bg-indigo-100 transition duration-150">
                </div>

                <div class="flex items-center pt-2">
                    <input id="upload-shared" type="checkbox" name="is_shared" class="h-4 w-4 text-indigo-600 border-gray-300 rounded focus:ring-indigo-500">
                    <label for="upload-shared" class="ml-2 block text-sm text-gray-900">Share with other instructors/users?</label>
                </div>


                <!-- Modal Footer (Submit) -->
                <div class="pt-4 flex justify-end space-x-3">
                    <button type="button" id="cancel-upload" class="py-2 px-4 rounded-lg text-gray-600 hover:bg-gray-100 transition duration-150">Cancel</button>
                    <button type="submit" class="bg-indigo-600 hover:bg-indigo-700 text-white font-medium py-2 px-4 rounded-lg shadow-md transition duration-150 ease-in-out">
                        Submit Resource
                    </button>
                </div>
            </form>

        </div>
    </div>
</div>



<script>
const uploadModal = document.getElementById('upload-modal');
const openModalBtn = document.getElementById('open-upload-modal');
const closeModalBtn = document.getElementById('close-upload-modal');
const cancelUploadBtn = document.getElementById('cancel-upload');
const uploadForm = document.getElementById('upload-form');

openModalBtn.addEventListener('click', () => {
    uploadModal.classList.remove('hidden');
});

const hideModal = () => {
    uploadModal.classList.add('hidden');
    uploadForm.reset(); // Clear the form on close
};

[closeModalBtn, cancelUploadBtn].forEach(btn => {
    btn.addEventListener('click', hideModal);
});

// Simple form submission handler (simulated)
uploadForm.addEventListener('submit', (e) => {
    e.preventDefault();

    const title = document.getElementById('upload-title').value;
    const fileInput = document.getElementById('upload-file');

    if (fileInput.files.length === 0) {
        // In a real app, this would be an inline error message
        console.error("Please select a file.");
        return;
    }

    console.log(`Simulating upload for: ${title}`);

    // In a real application, you would handle the file upload and database insertion here.
    // For this redesign, we just hide the modal and provide feedback.
    alertUserMessage('success', `Resource "${title}" uploaded successfully! (Simulated)`);
    hideModal();
});

// --- 5. INITIALIZATION ---

function alertUserMessage(type, message) {
    // A simple placeholder for showing messages instead of alert()
    const existingAlert = document.getElementById('app-alert');
    if (existingAlert) existingAlert.remove();

    const color = type === 'success' ? 'bg-green-100 text-green-800 border-green-400' : 'bg-red-100 text-red-800 border-red-400';

    const alertHtml = `
        <div id="app-alert" class="fixed top-4 right-4 z-50 p-4 rounded-lg shadow-xl border ${color} transition duration-300 transform translate-y-0" role="alert">
            <p class="font-medium">${message}</p>
        </div>
    `;
    document.body.insertAdjacentHTML('beforeend', alertHtml);

    // Automatically remove after 5 seconds
    setTimeout(() => {
        const currentAlert = document.getElementById('app-alert');
        if (currentAlert) currentAlert.remove();
    }, 5000);
}

window.onload = function() {
    // Initialization code can go here
};
</script>


<?php
// Helper functions
function getResourceTypeFromExtension($extension) {
    $types = [
        'pdf' => 'document',
        'doc' => 'document',
        'docx' => 'document',
        'ppt' => 'document',
        'pptx' => 'document',
        'xls' => 'document',
        'xlsx' => 'document',
        'txt' => 'document',
        'mp3' => 'audio',
        'wav' => 'audio',
        'jpg' => 'image',
        'jpeg' => 'image',
        'png' => 'image',
        'gif' => 'image',
        'zip' => 'archive',
        'rar' => 'archive',
        '7z' => 'archive'
    ];
    return $types[$extension] ?? 'other';
}

function validateResourceFile($extension, $size) {
    $allowedExtensions = ['pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'txt', 'mp3', 'wav', 'jpg', 'jpeg', 'png', 'gif', 'zip', 'rar', '7z'];
    $maxSize = 100 * 1024 * 1024; // 100MB

    return in_array(strtolower($extension), $allowedExtensions) && $size <= $maxSize;
}

function getResourceIcon($type) {
    // This is handled in JavaScript now
    return '';
}

function formatFileSize($bytes) {
    // This is handled in JavaScript now
    return '';
}

?>