<h2 style="margin-bottom:15px;">Students</h2>


<style>
    .table-card {
        background: #fff;
        padding: 20px;
        border-radius: 12px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    }

    .action-btn {
        padding: 6px 10px;
        border-radius: 6px;
        font-size: 13px;
        text-decoration: none;
        color: #fff;
        margin-right: 5px;
    }

    .btn-edit {
        background: #3b82f6;
    }

    .btn-delete {
        background: #ef4444;
    }

    .btn-edit:hover {
        background: #2563eb;
    }

    .btn-delete:hover {
        background: #dc2626;
    }
</style>

<% if (typeof error_msg !=='undefined' && error_msg) { %>

    <div class="alert alert-danger">
        <%= error_msg %>
    </div>

    <% } %>


        <% if (typeof success_msg !=='undefined' && success_msg) { %>
            <div class="alert alert-success">
                <%= success_msg %>
            </div>
            <% } %>

                <div class="table-card">
                    <div style="display:flex; gap:10px; align-items:center; margin-bottom:15px;">
                        <select class="filter-select" id="courseFilter" style="padding:8px; border-radius:6px;">
                            <option value="">All Courses</option>
                            <% courses.forEach(course=> { %>
                                <option value="<%= course._id %>">
                                    <%= course.title %>
                                </option>
                                <% }) %>
                        </select>
                        <select class="filter-select" id="batchFilter" style="padding:8px; border-radius:6px;">
                            <option value="">All Active Batches</option>
                            <% batches.forEach(batch=> { %>
                                <option value="<%= batch._id %>">
                                    <%= batch.title %>
                                </option>
                                <% }) %>
                        </select>




                        <button id="openEmailModal"
                            style="padding:8px 12px; background:#0f172a; color:#fff; border:none; border-radius:6px;">
                            Send Email to Course Students
                        </button>


                    </div>


                    <div style="display: flex; justify-content: flex-end; margin-bottom: 15px;">
                        <button onclick="addStudent()"
                            style="padding:8px 12px; background:#0f172a; color:#fff; border:none; border-radius:6px;">
                            Add Student
                        </button>
                    </div>
                    <div id="tableLoader" style="
    display:flex;
    justify-content:center;
    align-items:center;
    padding:20px;
">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">Loading...</span>
                        </div>
                    </div>
                    <table id="studentsTable" class="display datatable" style="width:100%; visibility:hidden;">

                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Name</th>
                                <th>Email</th>
                                <th>Course</th>
                                <th>Batch</th>
                                <th>Action</th>
                            </tr>
                        </thead>

                        <tbody>


                            <% students.forEach((student, index)=> { %>
                               <tr
                                data-course-ids="<%= student.courses.map(c => c._id.toString()).join(',') %>"
                                data-batch-ids="<%= student.batches.map(b => b._id.toString()).join(',') %>"
                            >
                                    <td>
                                        <%= index + 1 %>
                                    </td>
                                    <td>
                                        <%= student.name || '-' %>
                                    </td>
                                    <td>
                                        <%= student.email || '-' %>
                                    </td>


                                    <td>
                                        <% student.courses.slice(0, 1).forEach(course=> { %>
                                            <span style="
            display:inline-block;
            background:#e0f2fe;
            color:#0369a1;
            padding:3px 8px;
            border-radius:12px;
            font-size:12px;">
                                                <%= course.title %>
                                            </span>
                                            <% }) %>

                                                <% if(student.courses.length> 1){ %>

                                                    <span style="font-size:12px;color:#666;">
                                                        +<%= student.courses.length-1 %> more
                                                    </span>

                                                    <button class="viewCoursesBtn" type="button"
                                                        data-courses='<%- JSON.stringify(student.courses.map(c => c.title)) %>'
                                                        data-id="<%= student._id %>" style="
                border:none;
                background:none;
                color:#2563eb;
                cursor:pointer;
                font-size:12px;
                text-decoration:underline;">
                                                        View
                                                    </button>

                                                    <% } %>
                                    </td>
                                    <td>
                                        <% student.batches.slice(0, 1).forEach(batch=> { %>
                                            <span style="
            display:inline-block;
            background:#e0f2fe;
            color:#0369a1;
            padding:3px 8px;
            border-radius:12px;
            font-size:12px;">
                                                <%= batch.title %>
                                            </span>
                                            <% }) %>

                                                <% if(student.batches.length> 1){ %>

                                                    <span style="font-size:12px;color:#666;">
                                                        +<%= student.batches.length-1 %> more
                                                    </span>

                                                    <button class="viewBatchesBtn" type="button"
                                                        data-batches='<%- JSON.stringify(student.batches.map(b => b.title)) %>'
                                                        data-id="<%= student._id %>" style="
                border:none;
                background:none;
                color:#2563eb;
                cursor:pointer;
                font-size:12px;
                text-decoration:underline;">
                                                        View
                                                    </button>

                                                    <% } %>
                                    </td>


                                    <td class="action-column">

                                        <!-- EDIT -->


                                        <a href="<%= ROUTES.STUDENT_EDIT.replace(':id', student._id) %>"
                                            class="action-btn btn-edit">
                                            ✏ Edit
                                        </a>

                                        <!-- DELETE -->
                                        <a href="javascript:void(0);" class="action-btn btn-delete"
                                            onclick="confirmDelete('<%= ROUTES.STUDENT_DELETE.replace(':id', student._id) %>')">
                                            🗑 Delete
                                        </a>

                                    </td>
                                </tr>
                                <% }) %>


                        </tbody>

                    </table>

                </div>

                <div id="emailModal" style="
    display:none;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.5);
    justify-content:center;
    align-items:center;
    z-index:9999;
">

                    <!-- Modal Box -->
                    <div style="
        width:400px;
        background:#fff;
        border-radius:12px;
        padding:20px;
        box-shadow:0 10px 30px rgba(0,0,0,0.2);
        position:relative;
    ">

                        <h3 style="margin-bottom:15px;">Send Email</h3>

                        <!-- Close Button -->
                        <span id="closeModal" style="
            position:absolute;
            top:10px;
            right:15px;
            cursor:pointer;
            font-size:18px;
        ">✖</span>

                        <form action="<%= ROUTES.ADMIN_COURSE_EMAIL_SEND %>" method="POST">

                            <input type="hidden" name="course" id="selectedCourse">

                            <div style="margin-bottom:10px;">
                                <label>Subject</label>
                                <input type="text" name="subject" required
                                    style="width:100%; padding:8px; margin-top:5px;">
                            </div>

                            <div style="margin-bottom:10px;">
                                <label>Message</label>
                                <textarea name="message" rows="5" required
                                    style="width:100%; padding:8px; margin-top:5px;"></textarea>
                            </div>

                            <button type="submit" style="
                width:100%;
                padding:10px;
                background:#2563eb;
                color:#fff;
                border:none;
                border-radius:6px;
            ">
                                Send Email
                            </button>

                        </form>
                    </div>
                </div>
                <!-- JS -->




                <script>
                    $(document).ready(function () {
                        const table = $('#studentsTable').DataTable({
                            language: {
                                emptyTable: "No students found"
                            },
                            pageLength: 10,
                            responsive: true,
                            deferRender: true,
                            processing: true,
                            initComplete: function () {
                                $('#tableLoader').hide();

                                // show table
                                // $('#studentsTable').fadeIn(200);
                                $('#studentsTable').css('visibility', 'visible');
                            }
                        });

                        $.fn.dataTable.ext.search.push(function (settings, data, dataIndex) {

                            if (settings.nTable.id !== "studentsTable") {
                                return true;
                            }

                            const selectedCourse = $('#courseFilter').val();
                            const selectedBatch = $('#batchFilter').val();

                            if (!selectedCourse && !selectedBatch) {
                                return true;
                            }

                            const row = table.row(dataIndex).node();

                            const courseIds = ($(row).attr("data-course-ids") || "").split(",");
                            const batchIds = ($(row).attr("data-batch-ids") || "").split(",");

                            const courseMatched =
                                !selectedCourse || courseIds.includes(selectedCourse);

                            const batchMatched =
                                !selectedBatch || batchIds.includes(selectedBatch);

                            return courseMatched && batchMatched;
                        });
                        // redraw
                        $('#courseFilter, #batchFilter').on('change', function () {
                            table.draw();
                        });



                        // open email box
                        $('#openEmailModal').on('click', function () {
                            var course = $('#courseFilter').val();

                            if (!course) {

                                Swal.fire({
                                    icon: 'warning',
                                    title: 'Course Required',
                                    text: 'Please select a course first!',
                                    confirmButtonColor: '#10b981'
                                });
                                return;
                            }

                            $('#selectedCourse').val(course);
                            $('#emailModal').css('display', 'flex');

                            // ❌ disable body scroll (optional but good UX)
                            $('body').css('overflow', 'hidden');
                        });

                        $('#closeModal').on('click', function () {
                            closeModal();
                        });

                        function closeModal() {
                            $('#emailModal').hide();
                            $('body').css('overflow', 'auto');
                        }

                        // ❌ prevent background click close
                        $('#emailModal').on('click', function (e) {
                            e.stopPropagation(); // important
                        });

                        // ❌ disable ESC key close
                        $(document).on('keydown', function (e) {
                            if (e.key === "Escape") {
                                e.preventDefault();
                                return false;
                            }
                        });

                        $("#closeCoursesModal").on("click", function () {
                            $("#coursesModal").hide();
                        });
                        $("#closeBatchesModal").on("click", function () {
                            $("#batchesModal").hide();
                        });


                        $(document).on("click", ".viewCoursesBtn", function () {

                            const courses = JSON.parse($(this).attr("data-courses"));

                            let html = "";

                            courses.forEach(c => {
                                html += `
                            <span style="
                                display:inline-block;
                                margin:5px;
                                padding:6px 12px;
                                background:#e0f2fe;
                                color:#0369a1;
                                border-radius:15px;
                                font-size:13px;">
                                ${c}
                            </span>
                                     `;
                            });

                            $("#coursesList").html(html);
                            $("#coursesModal").css("display", "flex");

                        });

                        $(document).on("click", ".viewBatchesBtn", function () {

                            const batches = JSON.parse($(this).attr("data-batches"));

                            let html = "";

                            batches.forEach(b => {
                                html += `
                            <span style="
                                display:inline-block;
                                margin:5px;
                                padding:6px 12px;
                                background:#e0f2fe;
                                color:#0369a1;
                                border-radius:15px;
                                font-size:13px;">
                                ${b}
                            </span>
                                     `;
                            });

                            $("#batchesList").html(html);
                            $("#batchesModal").css("display", "flex");

                        });
                    });

                    function confirmDelete(url) {
                        Swal.fire({
                            title: "Are you sure?",
                            text: "This student will be permanently deleted!",
                            icon: "warning",
                            showCancelButton: true,
                            confirmButtonColor: "#d33",
                            cancelButtonColor: "#3085d6",
                            confirmButtonText: "Yes, delete it!"
                        }).then((result) => {
                            if (result.isConfirmed) {
                                window.location.href = url;
                            }
                        });
                    }
                    function addStudent() {
                        const courses = <%- JSON.stringify(courses) %>;
                        if (courses.length === 0) {
                            Swal.fire({
                                icon: 'warning',
                                title: 'No Courses Available',
                                text: 'Please add a course first before adding students.',
                                confirmButtonColor: '#10b981'
                            });
                            return;
                        } else {
                            window.location.href = "<%= ROUTES.STUDENT_ADD %>";
                        }
                    }
                </script>