<?php
require_once '../includes/middleware.php';
require_once '../config/database.php';
require_once '../includes/functions.php';

$db = getDB();

// Check if user is instructor or admin
anyRoleMiddleware(['instructor', 'admin']);

$user = getUserContext();
$userId = $_SESSION['user_id'];

// Handle POST requests for enroll/unenroll
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'enroll') {
        $courseId = $_POST['course_id'] ?? 0;
        $studentEmail = trim($_POST['student_email'] ?? '');
        if ($courseId && $studentEmail) {
            // Find student
            $stmt = $db->prepare("SELECT id FROM users WHERE email = ?");
            $stmt->execute([$studentEmail]);
            $student = $stmt->fetch();
            if ($student) {
                $result = enrollStudent($db, $courseId, $student['id'], $userId);
                $_SESSION['message'] = $result['message'];
                $_SESSION['message_type'] = $result['success'] ? 'success' : 'error';
            } else {
                $_SESSION['message'] = 'Student not found with that email.';
                $_SESSION['message_type'] = 'error';
            }
        } else {
            $_SESSION['message'] = 'Course and student email are required.';
            $_SESSION['message_type'] = 'error';
        }
    } elseif ($action === 'unenroll') {
        $enrollmentId = $_POST['enrollment_id'] ?? 0;
        if ($enrollmentId) {
            $result = unenrollStudent($db, $enrollmentId, $userId);
            $_SESSION['message'] = $result['message'];
            $_SESSION['message_type'] = $result['success'] ? 'success' : 'error';
        } else {
            $_SESSION['message'] = 'Enrollment ID required.';
            $_SESSION['message_type'] = 'error';
        }
    }
    // Redirect to avoid resubmission
    header('Location: ' . $_SERVER['PHP_SELF']);
    exit;
}

// Get filter parameters
$courseFilter = $_GET['course'] ?? '';
$statusFilter = $_GET['status'] ?? '';
$search = $_GET['search'] ?? '';

// 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 students
$query = "
    SELECT
        u.id as student_id,
        u.username,
        u.email,
        up.first_name,
        up.last_name,
        ce.id as enrollment_id,
        ce.enrollment_date,
        ce.status as enrollment_status,
        ce.progress_percentage,
        c.id as course_id,
        c.title as course_title,
        c.level as course_level,
        COUNT(DISTINCT cl.id) as total_lessons,
        COUNT(DISTINCT CASE WHEN clp.status = 'completed' THEN clp.lesson_id END) as completed_lessons
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    JOIN users u ON ce.student_id = u.id
    LEFT JOIN user_profiles up ON u.id = up.user_id
    LEFT JOIN course_lessons cl ON c.id = cl.course_id
    LEFT JOIN course_lesson_progress clp ON cl.id = clp.lesson_id AND clp.enrollment_id = ce.id
    WHERE c.instructor_id = ?
";

$params = [$userId];

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

if ($statusFilter) {
    $query .= " AND ce.status = ?";
    $params[] = $statusFilter;
}

if ($search) {
    $query .= " AND (u.username LIKE ? OR u.email LIKE ? OR CONCAT(up.first_name, ' ', up.last_name) LIKE ?)";
    $searchParam = "%$search%";
    $params[] = $searchParam;
    $params[] = $searchParam;
    $params[] = $searchParam;
}

$query .= " GROUP BY ce.id ORDER BY ce.enrollment_date DESC";

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

// Get summary statistics
$stmt = $db->prepare("
    SELECT
        COUNT(DISTINCT ce.student_id) as total_students,
        COUNT(ce.id) as total_enrollments,
        COUNT(CASE WHEN ce.status = 'completed' THEN 1 END) as completed_enrollments,
        AVG(ce.progress_percentage) as avg_progress
    FROM course_enrollments ce
    JOIN courses c ON ce.course_id = c.id
    WHERE c.instructor_id = ?
");
$stmt->execute([$userId]);
$stats = $stmt->fetch();

// Functions for enroll/unenroll
function enrollStudent($db, $courseId, $studentId, $instructorId) {
    try {
        // Check if course belongs to instructor
        $stmt = $db->prepare("SELECT id FROM courses WHERE id = ? AND instructor_id = ?");
        $stmt->execute([$courseId, $instructorId]);
        if (!$stmt->fetch()) {
            return ['success' => false, 'message' => 'You do not own this course.'];
        }
        // Check if already enrolled
        $stmt = $db->prepare("SELECT id FROM course_enrollments WHERE course_id = ? AND student_id = ? AND status != 'dropped'");
        $stmt->execute([$courseId, $studentId]);
        if ($stmt->fetch()) {
            return ['success' => false, 'message' => 'Student is already enrolled in this course.'];
        }
        // Enroll
        $stmt = $db->prepare("INSERT INTO course_enrollments (course_id, student_id, status, enrollment_date) VALUES (?, ?, 'enrolled', NOW())");
        if ($stmt->execute([$courseId, $studentId])) {
            return ['success' => true, 'message' => 'Student enrolled successfully.'];
        } else {
            return ['success' => false, 'message' => 'Failed to enroll student.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

function unenrollStudent($db, $enrollmentId, $instructorId) {
    try {
        // Check if enrollment belongs to instructor's course
        $stmt = $db->prepare("SELECT ce.id FROM course_enrollments ce JOIN courses c ON ce.course_id = c.id WHERE ce.id = ? AND c.instructor_id = ?");
        $stmt->execute([$enrollmentId, $instructorId]);
        if (!$stmt->fetch()) {
            return ['success' => false, 'message' => 'Enrollment not found or access denied.'];
        }
        // Unenroll
        $stmt = $db->prepare("UPDATE course_enrollments SET status = 'dropped', updated_at = NOW() WHERE id = ?");
        if ($stmt->execute([$enrollmentId])) {
            return ['success' => true, 'message' => 'Student unenrolled successfully.'];
        } else {
            return ['success' => false, 'message' => 'Failed to unenroll student.'];
        }
    } catch (Exception $e) {
        return ['success' => false, 'message' => 'Error: ' . $e->getMessage()];
    }
}

$page_title = 'My Students - Mutalex Academy';
?>

<!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 CDN -->
    <script src="https://cdn.tailwindcss.com"></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>
        /* Custom Tailwind Configuration */
        :root {
            --primary: #007bff;
            --secondary: #6c757d;
            --success: #28a745;
            --danger: #dc3545;
        }
        .text-primary { color: var(--primary); }
        .bg-primary { background-color: var(--primary); }
        .bg-success { background-color: var(--success); }
        .bg-secondary { background-color: var(--secondary); }

        /* Ensure smooth scrolling and font */
        body { font-family: 'Inter', sans-serif; background-color: #f8f9fa; }

        /* Custom Styles for Dashboard Layout */
        .admin-sidebar {
            transition: transform 0.3s ease-in-out;
            min-width: 250px;
        }
        @media (max-width: 1024px) {
            .admin-sidebar {
                position: fixed;
                top: 0;
                left: 0;
                transform: translateX(-100%);
                z-index: 50;
                height: 100%;
            }
            .admin-container.sidebar-open .admin-sidebar {
                transform: translateX(0);
            }
            .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;
        }

        /* Progress bar styles */
        .progress-bar {
            height: 8px;
            background: #e9ecef;
            border-radius: 4px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #007bff, #0056b3);
            transition: width 0.3s ease;
        }
    </style>
</head>
<body class="antialiased">

<!-- 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="admin-container flex min-h-screen">
    <!-- Sidebar -->
    <div id="admin-sidebar" class="admin-sidebar bg-gray-800 text-white shadow-xl lg:sticky lg:top-0 h-screen overflow-y-auto">
        <div class="p-6 border-b border-gray-700">
            <h2 class="text-2xl font-extrabold text-blue-400">Mutalex Academy</h2>
            <p class="text-sm font-light text-gray-400 mt-1">Instructor Panel</p>
        </div>

        <nav class="p-4">
            <ul class="space-y-2">
                <li><a href="dashboard.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-chart-line w-5 h-5 mr-3"></i>Dashboard</a></li>
                <li><a href="courses/" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-graduation-cap w-5 h-5 mr-3"></i>My Courses</a></li>
                <li><a href="courses/new.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-plus-circle w-5 h-5 mr-3"></i>Create Course</a></li>
                <li><a href="/lms/instructor/questions/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-question-circle w-5 h-5 mr-3"></i>Question Bank</a></li>
                <li><a href="/lms/instructor/exams/index.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-clipboard-check w-5 h-5 mr-3"></i>Exams & Quizzes</a></li>
                <li><a href="students.php" class="flex items-center p-3 rounded-lg bg-gray-700 text-blue-300 font-semibold hover:bg-gray-700 transition duration-150"><i class="fas fa-users w-5 h-5 mr-3"></i>My Students</a></li>
                <li><a href="analytics.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-chart-bar w-5 h-5 mr-3"></i>Analytics</a></li>
                <li><a href="resources.php" class="flex items-center p-3 rounded-lg text-gray-300 hover:bg-gray-700 transition duration-150"><i class="fas fa-book-open w-5 h-5 mr-3"></i>Resources</a></li>
                <li class="pt-4 border-t border-gray-700 mt-4">
                    <a href="../logout.php" class="flex items-center p-3 rounded-lg text-red-400 hover:bg-gray-700 transition duration-150">
                        <i class="fas fa-sign-out-alt w-5 h-5 mr-3"></i>Logout
                    </a>
                </li>
            </ul>
        </nav>
    </div>

    <!-- Main Content -->
    <div class="admin-content flex-1 p-4 sm:p-6 lg:p-8">
        <!-- Header (Mobile Menu Button and Page Title) -->
        <div class="admin-header flex justify-between items-center pb-6 border-b border-gray-200 mb-6">
            <div class="flex items-center">
                <!-- Hamburger Menu for Mobile -->
                <button id="sidebar-toggle" class="lg:hidden p-2 mr-4 text-gray-600 hover:text-gray-900 rounded-lg focus:outline-none">
                    <i class="fas fa-bars text-xl"></i>
                </button>
                <div>
                    <h1 class="text-3xl font-bold text-gray-800">My Students</h1>
                    <p class="text-sm text-gray-600 mt-1">Manage and track your enrolled students</p>
                </div>
            </div>
        </div>

        <!-- Messages -->
        <?php if (isset($_SESSION['message'])): ?>
        <div class="bg-<?php echo $_SESSION['message_type'] === 'success' ? 'green' : 'red'; ?>-100 border border-<?php echo $_SESSION['message_type'] === 'success' ? 'green' : 'red'; ?>-400 text-<?php echo $_SESSION['message_type'] === 'success' ? 'green' : 'red'; ?>-700 px-4 py-3 rounded mb-6" role="alert">
            <?php echo htmlspecialchars($_SESSION['message']); ?>
        </div>
        <?php unset($_SESSION['message'], $_SESSION['message_type']); ?>
        <?php endif; ?>

        <!-- Statistics Cards -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-8">
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-blue-600"><?php echo $stats['total_students']; ?></h3>
                <p class="text-gray-500 mt-2">Total Students</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-green-600"><?php echo $stats['total_enrollments']; ?></h3>
                <p class="text-gray-500 mt-2">Total Enrollments</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-purple-600"><?php echo $stats['completed_enrollments']; ?></h3>
                <p class="text-gray-500 mt-2">Completed Courses</p>
            </div>
            <div class="bg-white p-6 rounded-xl shadow-lg border border-gray-100 text-center">
                <h3 class="text-3xl font-bold text-yellow-600"><?php echo round($stats['avg_progress'] ?? 0); ?>%</h3>
                <p class="text-gray-500 mt-2">Average Progress</p>
            </div>
        </div>

        <!-- Filters and Search -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <form method="GET" class="flex flex-col lg:flex-row gap-4">
                <div class="flex-1">
                    <label for="search" class="block text-sm font-medium text-gray-700 mb-2">Search Students</label>
                    <input type="text" id="search" name="search" value="<?php echo htmlspecialchars($search); ?>"
                           class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                           placeholder="Search by name, username, or email...">
                </div>
                <div>
                    <label for="course" class="block text-sm font-medium text-gray-700 mb-2">Filter by Course</label>
                    <select id="course" 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>
                    <label for="status" class="block text-sm font-medium text-gray-700 mb-2">Enrollment Status</label>
                    <select id="status" 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 Statuses</option>
                        <option value="enrolled" <?php echo $statusFilter === 'enrolled' ? 'selected' : ''; ?>>Enrolled</option>
                        <option value="in_progress" <?php echo $statusFilter === 'in_progress' ? 'selected' : ''; ?>>In Progress</option>
                        <option value="completed" <?php echo $statusFilter === 'completed' ? 'selected' : ''; ?>>Completed</option>
                        <option value="dropped" <?php echo $statusFilter === 'dropped' ? 'selected' : ''; ?>>Dropped</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-200">
                        <i class="fas fa-search mr-2"></i>Filter
                    </button>
                </div>
            </form>
        </div>

        <!-- Enroll Student Section -->
        <div class="bg-white rounded-xl shadow-lg p-6 mb-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Enroll a Student</h3>
            <form method="POST" class="flex flex-col lg:flex-row gap-4">
                <input type="hidden" name="action" value="enroll">
                <div class="flex-1">
                    <label for="enroll_course" class="block text-sm font-medium text-gray-700 mb-2">Select Course</label>
                    <select id="enroll_course" name="course_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                        <option value="">Choose a course</option>
                        <?php foreach ($courses as $course): ?>
                            <option value="<?php echo $course['id']; ?>"><?php echo htmlspecialchars($course['title']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="flex-1">
                    <label for="student_email" class="block text-sm font-medium text-gray-700 mb-2">Student Email</label>
                    <input type="email" id="student_email" name="student_email" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="student@example.com" required>
                </div>
                <div class="flex items-end">
                    <button type="submit" class="px-6 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition duration-200">
                        <i class="fas fa-user-plus mr-2"></i>Enroll Student
                    </button>
                </div>
            </form>
        </div>

        <!-- Students Table -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden">
            <?php if (empty($students)): ?>
                <div class="text-center py-12">
                    <i class="fas fa-users text-6xl text-gray-400 mb-4"></i>
                    <h4 class="text-xl font-semibold text-gray-800 mb-2">No students found</h4>
                    <p class="text-gray-500">No students are currently enrolled in your courses.</p>
                </div>
            <?php else: ?>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Student</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Course</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Progress</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Enrolled</th>
                                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php foreach ($students as $student): ?>
                                <tr class="hover:bg-gray-50">
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center flex-shrink-0">
                                                <i class="fas fa-user text-gray-500"></i>
                                            </div>
                                            <div class="ml-4">
                                                <div class="text-sm font-medium text-gray-900">
                                                    <?php echo htmlspecialchars($student['first_name'] && $student['last_name'] ? $student['first_name'] . ' ' . $student['last_name'] : $student['username']); ?>
                                                </div>
                                                <div class="text-sm text-gray-500"><?php echo htmlspecialchars($student['email']); ?></div>
                                            </div>
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="text-sm text-gray-900"><?php echo htmlspecialchars($student['course_title']); ?></div>
                                        <div class="text-sm text-gray-500 capitalize"><?php echo $student['course_level']; ?> level</div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <div class="flex items-center">
                                            <div class="flex-1 mr-4">
                                                <div class="progress-bar">
                                                    <div class="progress-fill" style="width: <?php echo $student['progress_percentage']; ?>%"></div>
                                                </div>
                                            </div>
                                            <span class="text-sm text-gray-500"><?php echo $student['progress_percentage']; ?>%</span>
                                        </div>
                                        <div class="text-xs text-gray-400 mt-1">
                                            <?php echo $student['completed_lessons']; ?>/<?php echo $student['total_lessons']; ?> lessons
                                        </div>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap">
                                        <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full
                                            <?php
                                            switch($student['enrollment_status']) {
                                                case 'completed': echo 'bg-green-100 text-green-800'; break;
                                                case 'in_progress': echo 'bg-blue-100 text-blue-800'; break;
                                                case 'enrolled': echo 'bg-blue-100 text-blue-800'; break;
                                                case 'dropped': echo 'bg-red-100 text-red-800'; break;
                                                default: echo 'bg-gray-100 text-gray-800';
                                            }
                                            ?>">
                                            <?php echo ucfirst(str_replace('_', ' ', $student['enrollment_status'])); ?>
                                        </span>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                        <?php echo date('M j, Y', strtotime($student['enrollment_date'])); ?>
                                    </td>
                                    <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                        <div class="flex space-x-2">
                                            <button onclick="viewStudentProgress(<?php echo $student['student_id']; ?>, <?php echo $student['course_id']; ?>)"
                                                    class="text-blue-600 hover:text-blue-900" title="View Progress">
                                                <i class="fas fa-chart-line"></i>
                                            </button>
                                            <button onclick="contactStudent(<?php echo $student['student_id']; ?>)"
                                                    class="text-green-600 hover:text-green-900" title="Contact Student">
                                                <i class="fas fa-envelope"></i>
                                            </button>
                                            <form method="POST" style="display:inline;" onsubmit="return confirm('Are you sure you want to unenroll this student?')">
                                                <input type="hidden" name="action" value="unenroll">
                                                <input type="hidden" name="enrollment_id" value="<?php echo $student['enrollment_id']; ?>">
                                                <button type="submit" class="text-red-600 hover:text-red-900" title="Unenroll Student">
                                                    <i class="fas fa-user-times"></i>
                                                </button>
                                            </form>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
// Sidebar Toggle Logic
document.getElementById('sidebar-toggle').addEventListener('click', () => {
    document.querySelector('.admin-container').classList.toggle('sidebar-open');
});

// Close sidebar when clicking the overlay on mobile
document.getElementById('sidebar-overlay').addEventListener('click', () => {
    document.querySelector('.admin-container').classList.remove('sidebar-open');
});

// Ensure sidebar is always visible on large screens
window.addEventListener('resize', () => {
    if (window.innerWidth >= 1024) {
        document.querySelector('.admin-container').classList.remove('sidebar-open');
    }
});

// Student actions
function viewStudentProgress(studentId, courseId) {
    // Redirect to student progress page (to be implemented)
    window.location.href = `student_progress.php?student_id=${studentId}&course_id=${courseId}`;
}

function contactStudent(studentId) {
    // Open contact modal or redirect to messaging system
    alert('Contact functionality will be implemented. Student ID: ' + studentId);
}

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

    setTimeout(() => toast.classList.add('show'), 10);

    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 4000);
}
</script>

</body>
</html>