<?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 filters and search
$search = $_GET['search'] ?? '';
$type_filter = $_GET['type'] ?? '';
$difficulty_filter = $_GET['difficulty'] ?? '';
$category_filter = $_GET['category'] ?? '';
$status_filter = $_GET['status'] ?? (!hasRole('admin') ? 'approved' : '');
$course_filter = $_GET['course'] ?? '';

// Build query
$query = "
    SELECT q.*, qc.name as category_name, c.title as course_title,
            GROUP_CONCAT(DISTINCT qt.name) as tag_names
    FROM questions q
    LEFT JOIN question_categories qc ON q.category_id = qc.id
    LEFT JOIN courses c ON q.course_id = c.id
    LEFT JOIN question_tag_assignments qta ON q.id = qta.question_id
    LEFT JOIN question_tags qt ON qta.tag_id = qt.id
    WHERE q.instructor_id = ? OR q.is_shared = TRUE
";

$params = [$userId];

if (!empty($search)) {
    $query .= " AND (q.title LIKE ? OR q.content LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if (!empty($type_filter)) {
    $query .= " AND q.question_type = ?";
    $params[] = $type_filter;
}

if (!empty($difficulty_filter)) {
    $query .= " AND q.difficulty = ?";
    $params[] = $difficulty_filter;
}

if (!empty($category_filter)) {
    $query .= " AND q.category_id = ?";
    $params[] = $category_filter;
}

if (!empty($status_filter)) {
    $query .= " AND q.status = ?";
    $params[] = $status_filter;
}

if (!empty($course_filter)) {
    $query .= " AND q.course_id = ?";
    $params[] = $course_filter;
}

$query .= " GROUP BY q.id ORDER BY q.created_at DESC";

// Get questions
$stmt = $db->prepare($query);
$stmt->execute($params);
$questions = $stmt->fetchAll();

// Get filter options
$categories = $db->query("SELECT id, name FROM question_categories WHERE is_active = TRUE ORDER BY name")->fetchAll();
$courses = $db->prepare("SELECT id, title FROM courses WHERE instructor_id = ? ORDER BY title", [$userId])->fetchAll();

// Calculate stats
$totalQuestions = count($questions);
$sharedQuestions = count(array_filter($questions, fn($q) => $q['is_shared']));
$pendingQuestions = count(array_filter($questions, fn($q) => $q['status'] === 'pending_review'));
$lastUpdated = 'Today'; // or calculate from db

$page_title = 'Question Bank - ' . $lms_config['lms']['site_name'];
$active_link = 'questions';
?>
<!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: #10b981; }
        .toast-error { background-color: #ef4444; }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }

        /* Additional styles for questions page */
        .table-container {
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);
            border-radius: 12px;
            background: white;
            overflow: hidden;
        }

        .badge {
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .badge-easy { background: #dcfce7; color: #166534; }
        .badge-medium { background: #fef9c3; color: #854d0e; }
        .badge-hard { background: #fee2e2; color: #991b1b; }

        .status-approved { background: #e0f2fe; color: #075985; }
        .status-pending { background: #fef3c7; color: #92400e; }

        .search-input:focus {
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2);
            border-color: #3b82f6;
        }

        .action-btn {
            transition: all 0.2s ease;
        }

        .action-btn:hover {
            transform: translateY(-1px);
        }
    </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'; ?>

        <div class="p-8">
            <!-- Summary Stats -->
            <div class="grid grid-cols-1 md:grid-cols-4 gap-6 mb-8">
                <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
                    <p class="text-slate-500 text-xs font-bold uppercase tracking-wider mb-1">Total Questions</p>
                    <p class="text-2xl font-bold text-slate-800"><?php echo $totalQuestions; ?></p>
                </div>
                <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
                    <p class="text-slate-500 text-xs font-bold uppercase tracking-wider mb-1">Shared Questions</p>
                    <p class="text-2xl font-bold text-slate-800 text-blue-600"><?php echo $sharedQuestions; ?></p>
                </div>
                <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
                    <p class="text-slate-500 text-xs font-bold uppercase tracking-wider mb-1">Pending Approval</p>
                    <p class="text-2xl font-bold text-slate-800 text-amber-600"><?php echo $pendingQuestions; ?></p>
                </div>
                <div class="bg-white p-6 rounded-xl border border-slate-200 shadow-sm">
                    <p class="text-slate-500 text-xs font-bold uppercase tracking-wider mb-1">Last Updated</p>
                    <p class="text-2xl font-bold text-slate-800"><?php echo $lastUpdated; ?></p>
                </div>
            </div>

            <!-- Toolbar -->
            <div class="flex flex-col lg:flex-row gap-4 mb-6 justify-between items-start lg:items-center">
                <form method="GET" class="flex flex-wrap gap-3">
                    <select name="type" class="px-4 py-2 rounded-lg border bg-white text-sm text-slate-600 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
                        <option value="">All Types</option>
                        <option value="mcq_single" <?php echo $type_filter === 'mcq_single' ? 'selected' : ''; ?>>Multiple Choice (Single)</option>
                        <option value="mcq_multiple" <?php echo $type_filter === 'mcq_multiple' ? 'selected' : ''; ?>>Multiple Choice (Multiple)</option>
                        <option value="true_false" <?php echo $type_filter === 'true_false' ? 'selected' : ''; ?>>True/False</option>
                        <option value="essay" <?php echo $type_filter === 'essay' ? 'selected' : ''; ?>>Essay</option>
                        <option value="short_answer" <?php echo $type_filter === 'short_answer' ? 'selected' : ''; ?>>Short Answer</option>
                    </select>
                    <select name="difficulty" class="px-4 py-2 rounded-lg border bg-white text-sm text-slate-600 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
                        <option value="">Difficulty</option>
                        <option value="easy" <?php echo $difficulty_filter === 'easy' ? 'selected' : ''; ?>>Easy</option>
                        <option value="medium" <?php echo $difficulty_filter === 'medium' ? 'selected' : ''; ?>>Medium</option>
                        <option value="hard" <?php echo $difficulty_filter === 'hard' ? 'selected' : ''; ?>>Hard</option>
                    </select>
                    <select name="status" class="px-4 py-2 rounded-lg border bg-white text-sm text-slate-600 focus:outline-none focus:ring-2 focus:ring-blue-500/20">
                        <option value="">Status</option>
                        <option value="approved" <?php echo $status_filter === 'approved' ? 'selected' : ''; ?>>Approved</option>
                        <option value="pending_review" <?php echo $status_filter === 'pending_review' ? 'selected' : ''; ?>>Pending</option>
                    </select>
                    <button type="submit" class="px-4 py-2 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700">Apply Filters</button>
                </form>
                <div class="flex gap-3 w-full lg:w-auto">
                    <a href="import.php" class="flex-1 lg:flex-none px-5 py-2.5 bg-green-600 text-white rounded-lg text-sm font-medium hover:bg-green-700 action-btn flex items-center justify-center gap-2">
                        <i class="fas fa-file-import"></i> Import
                    </a>
                    <button onclick="exportQuestions()" class="flex-1 lg:flex-none px-5 py-2.5 bg-slate-800 text-white rounded-lg text-sm font-medium hover:bg-slate-700 action-btn flex items-center justify-center gap-2">
                        <i class="fas fa-file-export"></i> Export
                    </button>
                    <a href="new.php" class="flex-1 lg:flex-none px-5 py-2.5 bg-blue-600 text-white rounded-lg text-sm font-medium hover:bg-blue-700 action-btn flex items-center justify-center gap-2 shadow-lg shadow-blue-500/30">
                        <i class="fas fa-plus"></i> New Question
                    </a>
                </div>
            </div>

            <!-- Table -->
            <div class="table-container">
                <div class="overflow-x-auto">
                    <table class="w-full text-left">
                        <thead>
                            <tr class="bg-slate-50 border-b border-slate-200">
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Question Details</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Category / Course</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Difficulty</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase">Status</th>
                                <th class="px-6 py-4 text-xs font-bold text-slate-500 uppercase text-right">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-slate-100">
                            <?php if (empty($questions)): ?>
                            <tr>
                                <td colspan="5" class="px-6 py-8 text-center text-slate-500">
                                    No questions found. <a href="new.php" class="text-blue-600 hover:underline">Create your first question</a>.
                                </td>
                            </tr>
                            <?php else: ?>
                            <?php foreach ($questions as $question): ?>
                            <tr class="hover:bg-slate-50/80 transition-colors">
                                <td class="px-6 py-5">
                                    <div class="flex flex-col">
                                        <span class="text-slate-800 font-semibold mb-1 truncate max-w-xs"><?php echo htmlspecialchars($question['title']); ?></span>
                                        <div class="flex gap-2">
                                            <span class="text-[10px] bg-slate-100 text-slate-500 px-1.5 py-0.5 rounded"><?php echo strtoupper($question['question_type']); ?></span>
                                            <?php if ($question['tag_names']): ?>
                                            <span class="text-[10px] bg-blue-50 text-blue-500 px-1.5 py-0.5 rounded">#<?php echo htmlspecialchars($question['tag_names']); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </td>
                                <td class="px-6 py-5">
                                    <div class="flex flex-col">
                                        <span class="text-sm font-medium text-slate-700"><?php echo htmlspecialchars($question['category_name'] ?? 'Uncategorized'); ?></span>
                                        <span class="text-xs text-slate-400"><?php echo htmlspecialchars($question['course_title'] ?? ''); ?></span>
                                    </div>
                                </td>
                                <td class="px-6 py-5">
                                    <span class="badge badge-<?php echo $question['difficulty']; ?>"><?php echo ucfirst($question['difficulty']); ?></span>
                                </td>
                                <td class="px-6 py-5">
                                    <span class="badge status-<?php echo $question['status'] === 'approved' ? 'approved' : 'pending'; ?>"><?php echo ucfirst(str_replace('_', ' ', $question['status'])); ?></span>
                                </td>
                                <td class="px-6 py-5 text-right">
                                    <div class="flex justify-end gap-2">
                                        <button class="p-2 text-slate-400 hover:text-blue-600 transition-colors" title="Edit" onclick="window.location.href='edit.php?id=<?php echo $question['id']; ?>'"><i class="fas fa-pen text-sm"></i></button>
                                        <button class="p-2 text-slate-400 hover:text-red-600 transition-colors" title="Delete" onclick="deleteQuestion(<?php echo $question['id']; ?>)"><i class="fas fa-trash text-sm"></i></button>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <div class="bg-white px-6 py-4 border-t border-slate-200 flex items-center justify-between">
                    <span class="text-xs text-slate-500">Showing 1 to <?php echo count($questions); ?> of <?php echo $totalQuestions; ?> results</span>
                    <div class="flex gap-2">
                        <button class="px-3 py-1.5 border rounded-md text-sm text-slate-400 cursor-not-allowed">Previous</button>
                        <button class="px-3 py-1.5 border border-blue-600 bg-blue-50 text-blue-600 rounded-md text-sm font-semibold">1</button>
                        <button class="px-3 py-1.5 border rounded-md text-sm text-slate-600 hover:bg-slate-50">2</button>
                        <button class="px-3 py-1.5 border rounded-md text-sm text-slate-600 hover:bg-slate-50">3</button>
                        <button class="px-3 py-1.5 border rounded-md text-sm text-slate-600 hover:bg-slate-50">Next</button>
                    </div>
                </div>
            </div>
        </div>
    </main>
</div>

<!-- 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');
            });
        });
    }

    // Question-specific functions
    function exportQuestions() {
        // Get current filter values
        const urlParams = new URLSearchParams(window.location.search);
        const search = urlParams.get('search') || '';
        const type = urlParams.get('type') || '';
        const difficulty = urlParams.get('difficulty') || '';
        const category = urlParams.get('category') || '';
        const status = urlParams.get('status') || '';
        const course = urlParams.get('course') || '';

        // Build export URL with filters
        let exportUrl = 'export.php';
        const params = [];
        if (search) params.push('search=' + encodeURIComponent(search));
        if (type) params.push('type=' + encodeURIComponent(type));
        if (difficulty) params.push('difficulty=' + encodeURIComponent(difficulty));
        if (category) params.push('category=' + encodeURIComponent(category));
        if (status) params.push('status=' + encodeURIComponent(status));
        if (course) params.push('course=' + encodeURIComponent(course));

        if (params.length > 0) {
            exportUrl += '?' + params.join('&');
        }

        // Trigger download
        window.location.href = exportUrl;
    }

    function deleteQuestion(questionId) {
        if (confirm('Are you sure you want to delete this question? This action cannot be undone.')) {
            fetch('delete.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'question_id=' + questionId
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showToast('Question deleted successfully', 'success');
                    location.reload();
                } else {
                    showToast('Error deleting question: ' + data.message, 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showToast('Error deleting question', 'error');
            });
        }
    }
</script>
</body>
</html>