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

// Get all available courses for instructors to edit
$stmt = $db->prepare("
    SELECT c.*, COUNT(ce.id) as enrollment_count,
           COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) as completion_count,
           AVG(ce.progress_percentage) as avg_progress,
           COUNT(DISTINCT ce.student_id) as unique_students
    FROM courses c
    LEFT JOIN course_enrollments ce ON c.id = ce.course_id
    GROUP BY c.id
    ORDER BY c.created_at DESC
");
$stmt->execute();
$courses = $stmt->fetchAll();

// Get course categories for filter
$stmt = $db->query("SELECT * FROM course_categories WHERE is_active = 1 ORDER BY name");
$categories = $stmt->fetchAll();

$page_title = 'My Courses - ' . $lms_config['lms']['site_name'];
?>
<!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); }

        /* Rating Stars */
        .rating .fas.fa-star {
            color: #ddd; /* Unfilled */
        }
        .rating .fas.fa-star.filled {
            color: #ffc107; /* Filled (Yellow/Gold) */
        }
    </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">
    <!-- Sidebar Navigation (Desktop View) -->
    <aside class="hidden lg:block w-64 bg-white border-r border-accent-subtle p-6 shadow-sm sticky top-16 h-screen">
        <div class="flex flex-col h-full">
            <!-- Logo/Title -->
            <div class="text-xl font-extrabold text-primary-blue mb-10 tracking-wider">
                <?php echo htmlspecialchars($lms_config['lms']['site_name']); ?>
            </div>

            <!-- Navigation Links -->
            <nav class="space-y-2 flex-grow">
                <a href="../dashboard.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🏠</span>
                    <span>Dashboard</span>
                </a>
                <a href="index.php" class="flex items-center space-x-3 p-3 rounded-lg bg-primary-blue text-white font-semibold transition duration-150 shadow-md">
                    <span class="w-5 h-5">📚</span>
                    <span>My Courses</span>
                </a>
                <a href="new.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">➕</span>
                    <span>Create Course</span>
                </a>
                <a href="../questions/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">❓</span>
                    <span>Question Bank</span>
                </a>
                <a href="../exams/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">📝</span>
                    <span>Exams & Quizzes</span>
                </a>
                <a href="../students.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">👥</span>
                    <span>My Students</span>
                </a>
                <a href="../resources.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">📖</span>
                    <span>Resources</span>
                </a>
                <a href="../grading/index.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🏆</span>
                    <span>Grades</span>
                </a>
                <a href="../../logout.php" class="flex items-center space-x-3 p-3 rounded-lg text-text-dark hover:bg-accent-subtle transition duration-150">
                    <span class="w-5 h-5">🚪</span>
                    <span>Logout</span>
                </a>
            </nav>

            <!-- Footer/User Info (Bottom of Sidebar) -->
            <div class="mt-8 pt-4 border-t border-accent-subtle">
                <p class="text-xs text-gray-500 mb-2">Authenticated User:</p>
                <p class="text-xs text-gray-700 truncate font-mono bg-accent-subtle p-1 rounded"><?php echo htmlspecialchars($user['username'] ?? 'Instructor'); ?></p>
            </div>
        </div>
    </aside>

    <!-- 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">My Courses</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">

        <!-- Mobile Navigation Overlay (Hidden by default) -->
        <div id="mobileMenu" class="fixed inset-0 bg-white z-20 p-6 transform -translate-x-full transition-transform duration-300 lg:hidden">
            <div class="flex justify-between items-center mb-10">
                <div class="text-xl font-extrabold text-primary-blue tracking-wider"><?php echo htmlspecialchars($lms_config['lms']['site_name']); ?></div>
                <button id="closeMobileMenu" class="text-3xl text-text-dark">&times;</button>
            </div>
            <nav class="space-y-4">
                <a href="../dashboard.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏠 Dashboard</a>
                <a href="index.php" class="block p-3 rounded-lg bg-primary-blue text-white font-semibold">📚 My Courses</a>
                <a href="new.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">➕ Create Course</a>
                <a href="../questions/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">❓ Question Bank</a>
                <a href="../exams/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📝 Exams & Quizzes</a>
                <a href="../students.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">👥 My Students</a>
                <a href="../resources.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">📖 Resources</a>
                <a href="../grading/index.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🏆 Grades</a>
                <a href="../../logout.php" class="block p-3 rounded-lg text-text-dark hover:bg-accent-subtle">🚪 Logout</a>
            </nav>
        </div>

        <!-- Courses Section -->
        <div class="p-6">
            <div class="dashboard-section bg-white p-6 rounded-xl shadow-lg border border-accent-subtle">
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-3xl font-bold text-gray-900">My Courses</h2>
                    <a href="new.php" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition">
                        <i class="fas fa-plus mr-2"></i>Create New Course
                    </a>
                </div>

                <!-- Filters -->
                <div class="mb-6 flex flex-wrap gap-4">
                    <select class="border border-gray-300 rounded-md px-3 py-2">
                        <option>All Status</option>
                        <option>Published</option>
                        <option>Draft</option>
                    </select>
                    <select class="border border-gray-300 rounded-md px-3 py-2">
                        <option>All Categories</option>
                        <?php foreach ($categories as $category): ?>
                            <option><?php echo htmlspecialchars($category['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <input type="text" placeholder="Search courses..." class="border border-gray-300 rounded-md px-3 py-2 flex-1 min-w-[200px]">
                </div>

                <!-- Courses Grid -->
                <?php if (empty($courses)): ?>
                    <div class="text-center py-12">
                        <i class="fas fa-book fa-4x text-gray-300 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-600 mb-2">No courses yet</h3>
                        <p class="text-gray-500 mb-6">Start by creating your first course to share knowledge with students.</p>
                        <a href="new.php" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-medium">
                            <i class="fas fa-plus mr-2"></i>Create Your First Course
                        </a>
                    </div>
                <?php else: ?>
                    <div class="courses-grid grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-6">
                        <?php foreach ($courses as $course): ?>
                            <div class="course-card border border-gray-200 p-5 rounded-xl shadow-md flex flex-col justify-between">
                                <!-- Course Thumbnail -->
                                <div class="h-48 bg-gray-200 flex items-center justify-center rounded-lg mb-4">
                                    <?php if ($course['thumbnail']): ?>
                                        <img src="../../<?php echo htmlspecialchars($course['thumbnail']); ?>" alt="Course thumbnail" class="w-full h-full object-cover rounded-lg">
                                    <?php else: ?>
                                        <i class="fas fa-book text-4xl text-gray-400"></i>
                                    <?php endif; ?>
                                </div>

                                <!-- Course Content -->
                                <div class="flex-grow">
                                    <div class="flex justify-between items-start mb-2">
                                        <h4 class="text-lg font-bold text-gray-800 truncate"><?php echo htmlspecialchars($course['title']); ?></h4>
                                        <span class="text-xs font-semibold px-2 py-0.5 rounded-full bg-<?php echo $course['status'] === 'published' ? 'green' : 'yellow'; ?>-100 text-<?php echo $course['status'] === 'published' ? 'green' : 'yellow'; ?>-800">
                                            <?php echo ucfirst($course['status']); ?>
                                        </span>
                                    </div>

                                    <p class="text-sm text-gray-600 mb-3 line-clamp-2"><?php echo htmlspecialchars($course['short_description'] ?: 'No description'); ?></p>

                                    <!-- Stats -->
                                    <div class="course-stats grid grid-cols-3 text-center py-4 border-y border-gray-100 my-3">
                                        <div class="stat">
                                            <span class="block text-2xl font-bold text-blue-600"><?php echo $course['enrollment_count']; ?></span>
                                            <span class="block text-xs text-gray-500 uppercase tracking-wider">Students</span>
                                        </div>
                                        <div class="stat border-x border-gray-200">
                                            <span class="block text-2xl font-bold text-purple-600"><?php echo $course['completion_count']; ?></span>
                                            <span class="block text-xs text-gray-500 uppercase tracking-wider">Completed</span>
                                        </div>
                                        <div class="stat">
                                            <span class="block text-2xl font-bold text-green-600"><?php echo round($course['avg_progress'] ?? 0); ?>%</span>
                                            <span class="block text-xs text-gray-500 uppercase tracking-wider">Avg Progress</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Actions -->
                                <div class="course-actions flex flex-wrap gap-2 justify-center mt-3">
                                    <a href="course_builder.php?id=<?php echo $course['id']; ?>" class="px-3 py-1 text-sm font-medium border border-blue-500 text-blue-500 rounded-lg hover:bg-blue-50 transition">Edit</a>
                                    <a href="lesson_editor.php?course_id=<?php echo $course['id']; ?>" class="px-3 py-1 text-sm font-medium border border-green-500 text-green-500 rounded-lg hover:bg-green-50 transition">Add Lessons</a>
                                    <a href="../../courses/detail.php?id=<?php echo $course['id']; ?>" target="_blank" class="px-3 py-1 text-sm font-medium border border-gray-500 text-gray-500 rounded-lg hover:bg-gray-50 transition">Preview</a>
                                    <a href="analytics.php?id=<?php echo $course['id']; ?>" class="px-3 py-1 text-sm font-medium border border-purple-500 text-purple-500 rounded-lg hover:bg-purple-50 transition">Analytics</a>
                                    <a href="lesson_preview.php?course_id=<?php echo $course['id']; ?>" class="px-3 py-1 text-sm font-medium border border-indigo-500 text-indigo-500 rounded-lg hover:bg-indigo-50 transition">Lesson Preview</a>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </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');
            });
        });
    }
</script>
</body>
</html>