<?php
require_once '../config/database.php';
require_once '../config/auth.php';
require_once '../config/rbac.php';
$lms_config = require '../config/lms.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);

$page_title = 'Resource Library';
$active_link = 'resources';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo htmlspecialchars($page_title); ?></title>
    <!-- Load Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Set up Tailwind configuration for Inter font and a professional color palette -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        'primary-blue': '#1E3A8A', // Deep Indigo/Navy
                        'background-light': '#F8FAFC', // Slate 50
                        'text-dark': '#1F2937', // Gray 800
                        'accent-subtle': '#E5E7EB', // Gray 200
                    },
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <!-- Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <style>
        /* Ensuring full page height and scrolling */
        html, body {
            height: 100%;
        }
        /* Custom scrollbar for a cleaner look */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-thumb {
            background-color: #D1D5DB; /* Gray 300 */
            border-radius: 4px;
        }
        ::-webkit-scrollbar-track {
            background-color: transparent;
        }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
            /* Using min-h-screen utility class */
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0; /* Always positioned at 0, use transform to hide */
                transform: translateX(-100%); /* Hidden by default on mobile */
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0); /* Show on mobile */
            }
            .admin-container.sidebar-open .sidebar-overlay {
                display: block;
            }
        }

        /* Sidebar Overlay for Mobile */
        .sidebar-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 40;
            display: none;
            transition: opacity 0.3s ease;
        }

        /* Toast Notification Styles */
        #toast-container {
            position: fixed;
            top: 1.5rem;
            right: 1.5rem;
            z-index: 100;
            display: flex;
            flex-direction: column;
            gap: 0.5rem;
            max-width: 350px;
        }

        .toast {
            padding: 1rem 1.5rem;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            color: white;
            opacity: 0;
            transform: translateX(100%);
            transition: opacity 0.3s ease-out, transform 0.3s ease-out;
        }

        .toast.show {
            opacity: 1;
            transform: translateX(0);
        }

        .toast-success { background-color: var(--success); }
        .toast-error { background-color: var(--danger); }

        /* Additional styles for resources */
        .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>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- Toast Notification Container -->
<div id="toast-container"></div>

<!-- Sidebar Overlay (for closing sidebar on mobile tap outside) -->
<div id="sidebar-overlay" class="sidebar-overlay lg:hidden"></div>

<div class="flex">
    <?php include 'includes/sidebar.php'; ?>

    <!-- Top Bar (Mobile/Desktop Header) -->
    <header class="bg-white shadow-sm fixed top-0 left-0 right-0 z-10 border-b border-accent-subtle">
        <div class="px-4 sm:px-6 lg:px-8 py-4 flex justify-between items-center">
            <div class="flex items-center space-x-3">
                <img src="../assets/images/logo_1757657555.jpg" alt="Instructor Panel Logo" class="h-10 w-10">
                <div>
                    <h1 class="text-xl font-bold text-primary-blue"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></h1>
                    <p class="text-sm text-gray-600"><?php echo htmlspecialchars($page_title); ?></p>
                </div>
            </div>

            <div class="flex items-center space-x-4">
                <span class="text-sm font-medium hidden sm:inline"><?php echo htmlspecialchars($user['username']); ?></span>
                <img class="h-10 w-10 rounded-full border-2 border-primary-blue object-cover" src="https://placehold.co/100x100/1E3A8A/ffffff?text=<?php echo substr(htmlspecialchars($user['username'] ?? 'I'), 0, 1); ?>" alt="User Avatar">
                <!-- Mobile Menu Button (Hamburger) -->
                <button class="lg:hidden p-2 rounded-lg text-text-dark hover:bg-accent-subtle ml-4" id="mobileMenuButton">
                    <span class="text-xl">☰</span>
                </button>
            </div>
        </div>
    </header>

    <!-- Main Content Area -->
    <main class="flex-1 overflow-y-auto pt-16">

        <?php include 'includes/mobile_menu.php'; ?>
        <!-- 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>

    </main>
</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>

<!-- Custom Confirmation Modal (Hidden by default) -->
<div id="confirmation-modal" class="fixed inset-0 bg-gray-900 bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white p-6 rounded-lg shadow-2xl max-w-sm w-full transform transition-all">
        <h3 class="text-xl font-bold text-gray-800 mb-4" id="modal-title">Confirm Action</h3>
        <p class="text-gray-600 mb-6" id="modal-message">Are you sure you want to perform this action?</p>
        <div class="flex justify-end space-x-3">
            <button id="modal-cancel" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition">Cancel</button>
            <button id="modal-confirm" class="px-4 py-2 text-white rounded-md transition"></button>
        </div>
    </div>
</div>


<script>
    // --- UI/Utility Functions ---

    // Function to show a dismissible toast notification
    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container');
        const toast = document.createElement('div');
        toast.className = `toast toast-${type}`; // Note: 'show' added below
        toast.innerHTML = `<i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'} mr-2"></i>${message}`;
        container.appendChild(toast);

        // Force repaint to start transition
        setTimeout(() => toast.classList.add('show'), 10);

        // Auto-dismiss after 4 seconds
        setTimeout(() => {
            toast.classList.remove('show');
            // Remove from DOM after transition finishes
            setTimeout(() => toast.remove(), 300);
        }, 4000);
    }

    // Function to handle the custom confirmation modal (replacing window.confirm)
    function showConfirmationModal(action, reviewId) {
        const modal = document.getElementById('confirmation-modal');
        const title = document.getElementById('modal-title');
        const message = document.getElementById('modal-message');
        const confirmButton = document.getElementById('modal-confirm');
        const cancelButton = document.getElementById('modal-cancel');

        const isApprove = action === 'approve';
        const actionText = isApprove ? 'Approve' : 'Reject';

        // Placeholder function to simulate the PHP action
        const performAction = () => {
            // In a real application, this would be an AJAX call:
            // fetch('api/review_action.php', { method: 'POST', body: JSON.stringify({ action: action, review_id: reviewId }) })
            // .then(response => response.json()).then(data => { ... })
            fetch('../api/reviews.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    action: action,
                    review_id: reviewId
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast(`Review ${actionText.toLowerCase()}d successfully.`, 'success');
                    modal.classList.add('hidden');
                    modal.classList.remove('flex');
                    // Reload or remove the review item from the UI
                    location.reload();
                } else {
                    showToast('Error: ' + data.error, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('An error occurred. Please try again.', 'error');
            });
        };

        // Set modal content
        title.textContent = `Confirm ${actionText}`;
        message.textContent = `Are you sure you want to ${actionText.toLowerCase()} this review? This action cannot be undone. (Review ID: ${reviewId})`;
        confirmButton.textContent = actionText;
        confirmButton.className = `px-4 py-2 text-white rounded-md transition ${isApprove ? 'bg-green-500 hover:bg-green-600' : 'bg-red-500 hover:bg-red-600'}`;

        // Show modal
        modal.classList.remove('hidden');
        modal.classList.add('flex');

        // Set listeners
        confirmButton.onclick = performAction;
        cancelButton.onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };

        // Allow clicking the overlay to close
        document.getElementById('sidebar-overlay').onclick = () => {
            modal.classList.add('hidden');
            modal.classList.remove('flex');
        };
    }

    // Mobile Menu Functionality
    const mobileMenuButton = document.getElementById('mobileMenuButton');
    const closeMobileMenu = document.getElementById('closeMobileMenu');
    const mobileMenu = document.getElementById('mobileMenu');

    if (mobileMenuButton && closeMobileMenu && mobileMenu) {
        mobileMenuButton.addEventListener('click', () => {
            mobileMenu.classList.remove('-translate-x-full');
        });

        closeMobileMenu.addEventListener('click', () => {
            mobileMenu.classList.add('-translate-x-full');
        });

        // Close menu when a link is clicked
        mobileMenu.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                mobileMenu.classList.add('-translate-x-full');
            });
        });
    }
</script>
</body>
</html>

<?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 '';
}

?>