<?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 selected exam
$selectedExamId = $_GET['exam_id'] ?? null;

// Get instructor's exams
$exams = $db->prepare("
    SELECT e.id, e.title, e.status, c.title as course_title,
           COUNT(ea.id) as assigned_count
    FROM exams e
    LEFT JOIN courses c ON e.course_id = c.id
    LEFT JOIN exam_access ea ON e.id = ea.exam_id
    WHERE e.instructor_id = ? AND e.status IN ('published', 'draft')
    GROUP BY e.id
    ORDER BY e.title
");
$exams->execute([$userId]);
$exams = $exams->fetchAll();

// Get students for selected exam
$students = [];
$examTitle = '';
if ($selectedExamId) {
    // Verify exam belongs to instructor and get exam title
    $examCheck = $db->prepare("SELECT id, title FROM exams WHERE id = ? AND instructor_id = ?");
    $examCheck->execute([$selectedExamId, $userId]);
    $examData = $examCheck->fetch();
    if (!$examData) {
        $selectedExamId = null;
    } else {
        $examTitle = $examData['title'];
        // Get students with assignment status
        $stmt = $db->prepare("
            SELECT u.id, u.username, u.email, up.first_name, up.last_name,
                   CASE WHEN ea.id IS NOT NULL THEN 1 ELSE 0 END as is_assigned,
                   ea.access_granted_at
            FROM users u
            LEFT JOIN user_profiles up ON u.id = up.user_id
            LEFT JOIN exam_access ea ON u.id = ea.student_id AND ea.exam_id = ?
            WHERE u.role = 'student'
            ORDER BY COALESCE(up.last_name, u.username), COALESCE(up.first_name, '')
        ");
        $stmt->execute([$selectedExamId]);
        $students = $stmt->fetchAll();
    }
}

$page_title = 'Exam 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;
        }

        /* 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; }

        /* Custom table styles */
        .assignments-table th {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
            position: sticky;
            top: 0;
            z-index: 10;
        }

        .assignments-table tbody tr:hover {
            background-color: #f9fafb;
        }

        .status-badge.assigned {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
            color: white;
        }

        .status-badge.not-assigned {
            background: linear-gradient(135deg, #6b7280 0%, #4b5563 100%);
            color: white;
        }
    </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'; ?>

        <!-- Assignments Content -->
        <div class="p-4 sm:p-6 lg:p-8">
            <div class="space-y-8">
                <!-- Exam Selection -->
                <div class="bg-white p-6 rounded-xl shadow-lg">
                    <h2 class="text-2xl font-bold text-gray-800 mb-4">Select Exam</h2>
                    <div class="max-w-md">
                        <label for="exam_select" class="block text-sm font-medium text-gray-700 mb-2">
                            <i class="fas fa-file-alt mr-1"></i>Choose an exam to manage assignments
                        </label>
                        <select id="exam_select" name="exam_id" 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="">Choose an exam...</option>
                            <?php foreach ($exams as $exam): ?>
                                <option value="<?php echo $exam['id']; ?>" <?php echo $selectedExamId == $exam['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($exam['title']); ?>
                                    <?php if ($exam['course_title']): ?>
                                        (<?php echo htmlspecialchars($exam['course_title']); ?>)
                                    <?php endif; ?>
                                    - <?php echo $exam['assigned_count']; ?> assigned
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>

                <?php if ($selectedExamId && !empty($students)): ?>
                    <!-- Students List -->
                    <div class="bg-white p-6 rounded-xl shadow-lg">
                        <div class="flex justify-between items-center mb-6">
                            <h2 class="text-2xl font-bold text-gray-800">
                                <i class="fas fa-users mr-2 text-blue-600"></i>
                                Students (<?php echo count($students); ?>)
                            </h2>
                            <div class="flex space-x-3">
                                <button onclick="assignAll()" class="px-4 py-2 bg-green-600 text-white rounded-lg shadow hover:bg-green-700 transition duration-150 text-sm font-medium">
                                    <i class="fas fa-plus mr-1"></i>Assign All
                                </button>
                                <button onclick="unassignAll()" class="px-4 py-2 bg-red-600 text-white rounded-lg shadow hover:bg-red-700 transition duration-150 text-sm font-medium">
                                    <i class="fas fa-minus mr-1"></i>Unassign All
                                </button>
                            </div>
                        </div>

                        <div class="overflow-x-auto">
                            <table class="assignments-table w-full border-collapse">
                                <thead>
                                    <tr class="border-b border-gray-200">
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Student Name</th>
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Email</th>
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Exam</th>
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Status</th>
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($students as $student): ?>
                                        <tr data-student-id="<?php echo $student['id']; ?>" class="border-b border-gray-100 hover:bg-gray-50">
                                            <td class="py-3 px-4">
                                                <div class="font-semibold text-gray-900">
                                                    <?php
                                                    $fullName = trim(($student['first_name'] ?? '') . ' ' . ($student['last_name'] ?? ''));
                                                    if (empty($fullName)) {
                                                        echo htmlspecialchars($student['username']);
                                                    } else {
                                                        echo htmlspecialchars($fullName);
                                                    }
                                                    ?>
                                                </div>
                                            </td>
                                            <td class="py-3 px-4 text-gray-600"><?php echo htmlspecialchars($student['email']); ?></td>
                                            <td class="py-3 px-4 text-gray-600"><?php echo htmlspecialchars($examTitle); ?></td>
                                            <td class="py-3 px-4">
                                                <?php if ($student['is_assigned']): ?>
                                                    <span class="status-badge assigned inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
                                                        <i class="fas fa-check mr-1"></i> Assigned
                                                        <?php if ($student['access_granted_at']): ?>
                                                            <small class="ml-1 opacity-75"><?php echo date('M j, Y', strtotime($student['access_granted_at'])); ?></small>
                                                        <?php endif; ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="status-badge not-assigned inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium">
                                                        <i class="fas fa-times mr-1"></i> Not Assigned
                                                    </span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="py-3 px-4">
                                                <?php if ($student['is_assigned']): ?>
                                                    <button onclick="unassignStudent(<?php echo $student['id']; ?>)" class="px-3 py-1 bg-red-600 text-white rounded text-sm font-medium hover:bg-red-700 transition duration-150">
                                                        <i class="fas fa-minus mr-1"></i>Unassign
                                                    </button>
                                                <?php else: ?>
                                                    <button onclick="assignStudent(<?php echo $student['id']; ?>)" class="px-3 py-1 bg-green-600 text-white rounded text-sm font-medium hover:bg-green-700 transition duration-150">
                                                        <i class="fas fa-plus mr-1"></i>Assign
                                                    </button>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php elseif ($selectedExamId && empty($students)): ?>
                    <div class="bg-white p-8 rounded-xl shadow-lg text-center">
                        <i class="fas fa-users fa-3x text-gray-400 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-900 mb-2">No Students Found</h3>
                        <p class="text-gray-600">There are no students in the system yet.</p>
                    </div>
                <?php else: ?>
                    <div class="bg-white p-8 rounded-xl shadow-lg text-center">
                        <i class="fas fa-file-alt fa-3x text-gray-400 mb-4"></i>
                        <h3 class="text-xl font-semibold text-gray-900 mb-2">Select an Exam</h3>
                        <p class="text-gray-600">Choose an exam from the dropdown above to manage student assignments.</p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </main>
</div>

<script>
let currentExamId = <?php echo $selectedExamId ? $selectedExamId : 'null'; ?>;

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

document.getElementById('exam_select').addEventListener('change', function() {
    const examId = this.value;
    if (examId) {
        window.location.href = 'assignments.php?exam_id=' + examId;
    } else {
        window.location.href = 'assignments.php';
    }
});

function assignStudent(studentId) {
    if (!currentExamId) return;

    fetch('../../api/exams/assignments.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            exam_id: currentExamId,
            student_id: studentId,
            action: 'assign'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('Exam assigned successfully!', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('Error: ' + data.error, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Failed to assign exam', 'error');
    });
}

function unassignStudent(studentId) {
    if (!currentExamId) return;

    if (!confirm('Are you sure you want to unassign this exam from the student?')) {
        return;
    }

    fetch('../../api/exams/assignments.php', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            exam_id: currentExamId,
            student_id: studentId,
            action: 'unassign'
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showToast('Exam unassigned successfully!', 'success');
            setTimeout(() => location.reload(), 1000);
        } else {
            showToast('Error: ' + data.error, 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showToast('Failed to unassign exam', 'error');
    });
}

function assignAll() {
    if (!currentExamId) return;

    if (!confirm('Are you sure you want to assign this exam to all students?')) {
        return;
    }

    // Get all unassigned students
    const unassignedRows = document.querySelectorAll('tr[data-student-id] .status-badge.not-assigned');
    const studentIds = Array.from(unassignedRows).map(badge => {
        return badge.closest('tr').dataset.studentId;
    });

    if (studentIds.length === 0) {
        showToast('All students are already assigned to this exam.', 'error');
        return;
    }

    showToast('Assigning exam to all students...', 'success');

    // Assign each student
    let completed = 0;
    studentIds.forEach(studentId => {
        fetch('../../api/exams/assignments.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                exam_id: currentExamId,
                student_id: parseInt(studentId),
                action: 'assign'
            })
        })
        .then(response => response.json())
        .then(data => {
            completed++;
            if (completed === studentIds.length) {
                showToast('All exams assigned successfully!', 'success');
                setTimeout(() => location.reload(), 1000);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            completed++;
            if (completed === studentIds.length) {
                showToast('Some assignments may have failed', 'error');
                setTimeout(() => location.reload(), 1000);
            }
        });
    });
}

function unassignAll() {
    if (!currentExamId) return;

    if (!confirm('Are you sure you want to unassign this exam from all students?')) {
        return;
    }

    // Get all assigned students
    const assignedRows = document.querySelectorAll('tr[data-student-id] .status-badge.assigned');
    const studentIds = Array.from(assignedRows).map(badge => {
        return badge.closest('tr').dataset.studentId;
    });

    if (studentIds.length === 0) {
        showToast('No students are assigned to this exam.', 'error');
        return;
    }

    showToast('Unassigning exam from all students...', 'success');

    // Unassign each student
    let completed = 0;
    studentIds.forEach(studentId => {
        fetch('../../api/exams/assignments.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                exam_id: currentExamId,
                student_id: parseInt(studentId),
                action: 'unassign'
            })
        })
        .then(response => response.json())
        .then(data => {
            completed++;
            if (completed === studentIds.length) {
                showToast('All exams unassigned successfully!', 'success');
                setTimeout(() => location.reload(), 1000);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            completed++;
            if (completed === studentIds.length) {
                showToast('Some unassignments may have failed', 'error');
                setTimeout(() => location.reload(), 1000);
            }
        });
    });
}

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