<?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 filter parameters
$courseFilter = $_GET['course'] ?? '';
$statusFilter = $_GET['status'] ?? 'all';

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

// Build query for assignments
$query = "
    SELECT
        cl.id as lesson_id,
        cl.title as lesson_title,
        cl.description as lesson_description,
        c.id as course_id,
        c.title as course_title,
        COUNT(DISTINCT ce.student_id) as total_students,
        COUNT(asub.id) as submitted_count,
        COUNT(CASE WHEN asub.status = 'graded' THEN 1 END) as graded_count
    FROM course_lessons cl
    JOIN courses c ON cl.course_id = c.id
    LEFT JOIN course_enrollments ce ON c.id = ce.course_id
    LEFT JOIN assignment_submissions asub ON cl.id = asub.lesson_id AND ce.id = asub.enrollment_id
    WHERE c.instructor_id = ? AND cl.lesson_type = 'assignment'
";

$params = [$userId];

if ($courseFilter) {
    $query .= " AND c.id = ?";
    $params[] = $courseFilter;
}

$query .= " GROUP BY cl.id, c.id ORDER BY c.title, cl.title";

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

// Get recent submissions for grading
$submissionsQuery = "
    SELECT
        asub.id,
        asub.submission_text,
        asub.attachment_path,
        asub.submitted_at,
        asub.grade,
        asub.feedback,
        asub.status,
        cl.title as lesson_title,
        c.title as course_title,
        u.username as student_name,
        up.first_name,
        up.last_name
    FROM assignment_submissions asub
    JOIN course_lessons cl ON asub.lesson_id = cl.id
    JOIN course_enrollments ce ON asub.enrollment_id = ce.id
    JOIN courses c ON cl.course_id = c.id
    JOIN users u ON ce.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    WHERE c.instructor_id = ?
";

$submissionsParams = [$userId];

if ($courseFilter) {
    $submissionsQuery .= " AND c.id = ?";
    $submissionsParams[] = $courseFilter;
}

if ($statusFilter !== 'all') {
    $submissionsQuery .= " AND asub.status = ?";
    $submissionsParams[] = $statusFilter;
}

$submissionsQuery .= " ORDER BY asub.submitted_at DESC LIMIT 20";

$stmt = $db->prepare($submissionsQuery);
$stmt->execute($submissionsParams);
$recentSubmissions = $stmt->fetchAll();

$page_title = 'Assignments - ' . $lms_config['lms']['site_name'];
$active_link = 'assignments';
?>

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

        /* 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;
        }
    </style>
</head>
<body class="bg-background-light font-sans text-text-dark min-h-screen">

<!-- 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">

        <!-- Filters -->
        <div class="bg-white p-6 rounded-xl shadow-lg mb-6">
            <form method="GET" class="flex flex-wrap gap-4">
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Course</label>
                    <select name="course" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="">All Courses</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo $course['id']; ?>" <?php echo $courseFilter == $course['id'] ? 'selected' : ''; ?>>
                                <?php echo htmlspecialchars($course['title']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="flex-1 min-w-[200px]">
                    <label class="block text-sm font-medium text-gray-700 mb-2">Status</label>
                    <select name="status" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                        <option value="all" <?php echo $statusFilter == 'all' ? 'selected' : ''; ?>>All Submissions</option>
                        <option value="submitted" <?php echo $statusFilter == 'submitted' ? 'selected' : ''; ?>>Pending Grading</option>
                        <option value="graded" <?php echo $statusFilter == 'graded' ? 'selected' : ''; ?>>Graded</option>
                        <option value="returned" <?php echo $statusFilter == 'returned' ? 'selected' : ''; ?>>Returned</option>
                    </select>
                </div>
                <div class="flex items-end">
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition duration-150">
                        <i class="fas fa-filter mr-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Assignment Overview -->
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6 mb-8">
            <!-- Assignment List -->
            <div class="bg-white p-6 rounded-xl shadow-lg">
                <h2 class="text-xl font-bold text-gray-800 mb-4">My Assignments</h2>
                <?php if (empty($assignments)): ?>
                    <div class="text-center py-8">
                        <i class="fas fa-tasks fa-3x text-gray-300 mb-4"></i>
                        <h3 class="text-lg font-semibold text-gray-900 mb-2">No assignments found</h3>
                        <p class="text-gray-600">Create assignment lessons in your courses to see them here.</p>
                    </div>
                <?php else: ?>
                    <div class="space-y-4">
                        <?php foreach ($assignments as $assignment): ?>
                            <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition duration-200">
                                <div class="flex justify-between items-start mb-2">
                                    <h3 class="font-semibold text-gray-900"><?php echo htmlspecialchars($assignment['lesson_title']); ?></h3>
                                    <span class="text-sm bg-blue-100 text-blue-800 px-2 py-1 rounded-full">
                                        <?php echo htmlspecialchars($assignment['course_title']); ?>
                                    </span>
                                </div>
                                <p class="text-sm text-gray-600 mb-3"><?php echo htmlspecialchars(substr($assignment['lesson_description'] ?? '', 0, 100)); ?>...</p>
                                <div class="flex justify-between items-center text-sm">
                                    <span class="text-gray-500">
                                        <i class="fas fa-users mr-1"></i><?php echo $assignment['submitted_count']; ?>/<?php echo $assignment['total_students']; ?> submitted
                                    </span>
                                    <span class="text-green-600">
                                        <i class="fas fa-check-circle mr-1"></i><?php echo $assignment['graded_count']; ?> graded
                                    </span>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Recent Submissions -->
            <div class="bg-white p-6 rounded-xl shadow-lg">
                <h2 class="text-xl font-bold text-gray-800 mb-4">Recent Submissions</h2>
                <?php if (empty($recentSubmissions)): ?>
                    <div class="text-center py-8">
                        <i class="fas fa-inbox fa-3x text-gray-300 mb-4"></i>
                        <h3 class="text-lg font-semibold text-gray-900 mb-2">No submissions yet</h3>
                        <p class="text-gray-600">Student submissions will appear here.</p>
                    </div>
                <?php else: ?>
                    <div class="space-y-4 max-h-96 overflow-y-auto">
                        <?php foreach ($recentSubmissions as $submission): ?>
                            <div class="border border-gray-200 rounded-lg p-4 hover:shadow-md transition duration-200">
                                <div class="flex justify-between items-start mb-2">
                                    <div>
                                        <h4 class="font-semibold text-gray-900"><?php echo htmlspecialchars($submission['first_name'] && $submission['last_name'] ? $submission['first_name'] . ' ' . $submission['last_name'] : $submission['student_name']); ?></h4>
                                        <p class="text-sm text-gray-600"><?php echo htmlspecialchars($submission['lesson_title']); ?></p>
                                        <p class="text-xs text-gray-500"><?php echo htmlspecialchars($submission['course_title']); ?></p>
                                    </div>
                                    <div class="text-right">
                                        <span class="text-xs px-2 py-1 rounded-full <?php
                                            echo $submission['status'] === 'submitted' ? 'bg-yellow-100 text-yellow-800' :
                                                 ($submission['status'] === 'graded' ? 'bg-green-100 text-green-800' : 'bg-blue-100 text-blue-800');
                                        ?>">
                                            <?php echo ucfirst($submission['status']); ?>
                                        </span>
                                        <p class="text-xs text-gray-500 mt-1"><?php echo date('M j, Y', strtotime($submission['submitted_at'])); ?></p>
                                    </div>
                                </div>
                                <?php if ($submission['grade']): ?>
                                    <div class="mt-2">
                                        <span class="text-sm font-medium text-green-600">Grade: <?php echo $submission['grade']; ?>%</span>
                                    </div>
                                <?php endif; ?>
                                <div class="mt-3 flex gap-2">
                                    <button onclick="viewSubmission(<?php echo $submission['id']; ?>)" class="text-xs bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700 transition duration-150">
                                        <i class="fas fa-eye mr-1"></i>View
                                    </button>
                                    <?php if ($submission['status'] === 'submitted'): ?>
                                        <button onclick="gradeSubmission(<?php echo $submission['id']; ?>)" class="text-xs bg-green-600 text-white px-3 py-1 rounded hover:bg-green-700 transition duration-150">
                                            <i class="fas fa-trophy mr-1"></i>Grade
                                        </button>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<?php include 'includes/mobile_menu.php'; ?>

<!-- Submission Modal -->
<div id="submissionModal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white rounded-xl shadow-2xl max-w-4xl w-full mx-4 max-h-[90vh] overflow-y-auto">
        <div class="p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-bold text-gray-900">Assignment Submission</h2>
                <button onclick="closeSubmissionModal()" class="text-gray-400 hover:text-gray-600">
                    <i class="fas fa-times w-6 h-6"></i>
                </button>
            </div>
            <div id="submissionContent">
                <!-- Content will be loaded here -->
            </div>
        </div>
    </div>
</div>

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

document.getElementById('sidebar-overlay').addEventListener('click', () => {
    if (mobileMenu) mobileMenu.classList.add('-translate-x-full');
});

function viewSubmission(submissionId) {
    // Load submission details
    fetch(`../api/assignment_details.php?id=${submissionId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const content = document.getElementById('submissionContent');
                content.innerHTML = `
                    <div class="space-y-6">
                        <div>
                            <h3 class="text-lg font-semibold text-gray-900 mb-2">${data.submission.lesson_title}</h3>
                            <p class="text-sm text-gray-600 mb-4">Submitted by: ${data.submission.student_name} on ${new Date(data.submission.submitted_at).toLocaleDateString()}</p>
                        </div>

                        <div>
                            <h4 class="font-medium text-gray-900 mb-2">Submission:</h4>
                            <div class="bg-gray-50 p-4 rounded-lg">
                                <p class="text-gray-800 whitespace-pre-wrap">${data.submission.submission_text || 'No text submission'}</p>
                            </div>
                        </div>

                        ${data.submission.attachment_path ? `
                            <div>
                                <h4 class="font-medium text-gray-900 mb-2">Attachment:</h4>
                                <a href="${data.submission.attachment_path}" target="_blank" class="inline-flex items-center gap-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition duration-150">
                                    <i class="fas fa-download"></i>Download Attachment
                                </a>
                            </div>
                        ` : ''}

                        ${data.submission.status === 'graded' ? `
                            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                                <h4 class="font-medium text-green-900 mb-2">Grading:</h4>
                                <p class="text-green-800"><strong>Grade:</strong> ${data.submission.grade}%</p>
                                ${data.submission.feedback ? `<p class="text-green-800 mt-2"><strong>Feedback:</strong> ${data.submission.feedback}</p>` : ''}
                            </div>
                        ` : ''}

                        <div class="flex justify-end gap-3">
                            ${data.submission.status === 'submitted' ? `
                                <button onclick="gradeSubmission(${submissionId})" class="bg-green-600 text-white px-6 py-2 rounded-lg hover:bg-green-700 transition duration-150">
                                    <i class="fas fa-trophy mr-2"></i>Grade Submission
                                </button>
                            ` : `
                                <button onclick="editGrade(${submissionId})" class="bg-blue-600 text-white px-6 py-2 rounded-lg hover:bg-blue-700 transition duration-150">
                                    <i class="fas fa-edit mr-2"></i>Edit Grade
                                </button>
                            `}
                            <button onclick="closeSubmissionModal()" class="bg-gray-600 text-white px-6 py-2 rounded-lg hover:bg-gray-700 transition duration-150">
                                Close
                            </button>
                        </div>
                    </div>
                `;
                document.getElementById('submissionModal').classList.remove('hidden');
                document.getElementById('submissionModal').classList.add('flex');
            } else {
                alert('Error loading submission: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('An error occurred while loading the submission.');
        });
}

function gradeSubmission(submissionId) {
    const grade = prompt('Enter grade (0-100):');
    if (grade === null) return;

    const feedback = prompt('Enter feedback (optional):');

    fetch('../api/grade_assignment.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            submission_id: submissionId,
            grade: parseFloat(grade),
            feedback: feedback
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Assignment graded successfully!');
            location.reload();
        } else {
            alert('Error grading assignment: ' + data.error);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('An error occurred while grading the assignment.');
    });
}

function editGrade(submissionId) {
    // Similar to gradeSubmission but for editing existing grades
    gradeSubmission(submissionId);
}

function closeSubmissionModal() {
    document.getElementById('submissionModal').classList.add('hidden');
    document.getElementById('submissionModal').classList.remove('flex');
}
</script>

</body>
</html>