<%- include('partials/header-sidebar') %>

    <div class="page-wrapper" id="toTop">
        <div class="content">
            <div class="page-header">
                <div class="page-title">
                    <h4>Manage Schools</h4>
                    <h6>Add/Update/Delete Shools</h6>
                </div>
            </div>

            <div class="card">
                <div class="card-body">
                    <div class="row">
                        <div class="col-lg-12">
                            <div class="form-group">
                                <label for="schoolName">School Name</label>
                                <input type="text" id="schoolName" class="form-control" placeholder="Enter School name">
                            </div>
                        </div>

                        <div class="col-lg-12">
                            <div class="form-group">
                                <label for="schoolDescription">Description</label>
                                <textarea id="schoolDescription" class="form-control"
                                    placeholder="Enter Short description"></textarea>
                            </div>
                        </div>

                        <div class="col-lg-12">
                            <a href="javascript:void(0);" id="createSchoolBtn" class="btn btn-submit me-2">Create
                                School</a>

                            <a href="javascript:void(0);" id="UpdateSchoolBtn" class="btn btn-submit me-2">Update
                                School</a>

                            <a href="javascript:void(0);" id="cancelUpdateBtn" onclick="cancelUpdate()"
                                class="btn btn-cancel me-2">Cancel</a>
                        </div>
                    </div>

                </div>
            </div>


            <!-- table to contain list of schools -->
            <div class="row">
                <div class="col-sm-12">
                    <div class="card">
                        <div class="card-header pb-0">
                            <h4 class="card-title mb-0">All School</h4>

                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table datanew">
                                    <thead>
                                        <tr>
                                            <th>Name of School</th>
                                            <th>Description</th>
                                            <th>Date created</th>
                                            <th>Actions</th>

                                        </tr>
                                    </thead>
                                    <tbody id="schoolTableBody">
                                        <!-- inserted from js -->
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    </div>


    <%- include("partials/footer") %>

        <script>
            document.addEventListener("DOMContentLoaded", () => {
                document.getElementById("UpdateSchoolBtn").style.display = "none";
                document.getElementById("cancelUpdateBtn").style.display = "none"

                let editingSchoolId = null;


            })
        </script>

        <script>
            document.getElementById("createSchoolBtn").addEventListener("click", async function () {
                const name = document.getElementById("schoolName").value.trim();
                const description = document.getElementById("schoolDescription").value.trim();
                const token = localStorage.getItem("token");

                console.log("The token on the schools is", token)

                if (!name) {
                    return Swal.fire("Error", "School name is required", "warning");
                }

                if (!description) {
                    return Swal.fire("Error", "Short description is required", "warning");
                }

                try {
                    const res = await fetch("/api/schools", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            "Authorization": `Bearer ${token}`,
                        },
                        body: JSON.stringify({ name, description }),
                    });

                    const data = await res.json()

                    if (!res.ok || !data.success) {
                        let message = "Failed to create school";

                        if (Array.isArray(data.message)) {
                            message = data.message.join("\n"); // or <br> if using html
                        } else if (typeof data.message === "string") {
                            message = data.message;
                        }

                        throw new Error(message);
                    }

                    Swal.fire("Success", "School created successfully!", "success");
                    document.getElementById("schoolName").value = "";
                    document.getElementById("schoolDescription").value = "";

                    loadSchools(); // Refresh table
                } catch (err) {
                    console.error(err);
                    Swal.fire("Error", err.message, "error");
                }
            });
        </script>


        <!-- LOAD SCHOOLS INTO TABLES -->

        <script>
            async function loadSchools() {
                const token = localStorage.getItem("token");

                try {
                    const res = await fetch("/api/schools", {
                        headers: {
                            Authorization: `Bearer ${token}`
                        }
                    });

                    const data = await res.json();
                    const schools = data.data;

                    // Destroy DataTable before rebuilding it
                    if ($.fn.DataTable.isDataTable('.datanew')) {
                        $('.datanew').DataTable().destroy();
                    }

                    const tbody = document.getElementById("schoolTableBody");
                    tbody.innerHTML = ""; // Clear old rows

                    schools.forEach(school => {
                        const row = document.createElement("tr");
                        row.innerHTML = `
                    <td>${school.name}</td>
                    <td>${school.description || "—"}</td>
                    <td>${new Date(school.createdAt).toLocaleDateString()}</td>
                    <td>
                        <span class="me-2 text-primary action-btns" onclick="editSchool('${school._id}')">
                            <i class="fas fa-pen me-1"></i>Edit
                        </span>
                        <span class="text-danger action-btns" onclick="confirmDeleteSchool('${school._id}')">
                            <i class="fas fa-trash me-1"></i>Delete
                        </span>
                    </td>
                `;
                        tbody.appendChild(row);
                    });

                    // Re-initialize DataTable after rows are inserted
                    $('.datanew').DataTable();

                } catch (err) {
                    Swal.fire("Error", "Failed to load schools", "error");
                    console.error(err);
                }
            }

            // Load on page start
            document.addEventListener("DOMContentLoaded", function () {
                loadSchools();
            });
        </script>



        <!-- DELETA WITH SWEET ALART -->

        <script>
            function confirmDeleteSchool(id) {
                Swal.fire({
                    title: "Are you sure?",
                    text: "This will permanently delete the school.",
                    icon: "warning",
                    showCancelButton: true,
                    confirmButtonText: "Yes, delete it!",
                    cancelButtonText: "Cancel"
                }).then(async (result) => {
                    if (result.isConfirmed) {
                        try {
                            const res = await fetch(`/api/schools/${id}`, {
                                method: "DELETE",
                                headers: {
                                    Authorization: `Bearer ${localStorage.getItem("token")}`
                                }
                            });

                            const data = await res.json()

                            if (!res.ok || !data.success) {
                                throw new Error("Failed to delete");
                            }

                            Swal.fire("Deleted!", "School has been deleted.", "success");
                            loadSchools();
                        } catch (err) {
                            console.error(err);
                            Swal.fire("Error", err.message, "error");
                        }
                    }
                });
            }


            // EDITING THE SCHOOL
            async function editSchool(id) {
                const token = localStorage.getItem("token");
                try {
                    const res = await fetch(`/api/schools?id=${id}`, {
                        headers: { Authorization: `Bearer ${token}` }
                    });
                    if (!res.ok) throw new Error("Failed to fetch school data");
                    const data = await res.json();
                    if (!data.success) throw new Error(data.message || "Failed to fetch school data");

                    // Fill the inputs
                    document.getElementById("schoolName").value = data.data.name;
                    document.getElementById("schoolDescription").value = data.data.description || "";

                    // Set current editing ID
                    editingSchoolId = id;

                    // Show Update button, hide Create button
                    document.getElementById("createSchoolBtn").style.display = "none";
                    document.getElementById("UpdateSchoolBtn").style.display = "inline-block";
                    document.getElementById('cancelUpdateBtn').style.display = "inline-block";

                    document.getElementById("toTop").scrollIntoView({ behavior: "smooth" });
                } catch (err) {
                    Swal.fire("Error", err.message, "error");
                }
            }


            document.getElementById("UpdateSchoolBtn").addEventListener("click", async function () {
                if (!editingSchoolId) {
                    return Swal.fire("Error", "No school selected for update", "warning");
                }

                const name = document.getElementById("schoolName").value.trim();
                const description = document.getElementById("schoolDescription").value.trim();
                const token = localStorage.getItem("token");

                if (!name) {
                    return Swal.fire("Error", "School name is required", "warning");
                }

                if (!description) {
                    return Swal.fire("Error", "Short description is required", "warning");
                }

                try {
                    const res = await fetch(`/api/schools/${editingSchoolId}`, {
                        method: "PUT", // or PATCH if your backend supports
                        headers: {
                            "Content-Type": "application/json",
                            Authorization: `Bearer ${token}`,
                        },
                        body: JSON.stringify({ name, description }),
                    });

                    const data = await res.json();

                    if (!res.ok || !data.success) {
                        let message = "Failed to update school";
                        if (Array.isArray(data.message)) {
                            message = data.message.join("<br>");
                        } else if (typeof data.message === "string") {
                            message = data.message;
                        }
                        return Swal.fire({
                            icon: "error",
                            title: "Error",
                            html: message,
                        });
                    }

                    Swal.fire("Success", "School updated successfully!", "success");

                    // Reset form and state
                    document.getElementById("schoolName").value = "";
                    document.getElementById("schoolDescription").value = "";
                    editingSchoolId = null;

                    // Show Create button, hide Update button
                    document.getElementById("createSchoolBtn").style.display = "inline-block";
                    document.getElementById("UpdateSchoolBtn").style.display = "none";
                    document.getElementById('cancelUpdateBtn').style.display = "none";

                    document.querySelector(".table-responsive").scrollIntoView({ behavior: "smooth" });

                    loadSchools(); // Refresh table
                } catch (err) {
                    console.error(err);
                    Swal.fire("Error", err.message, "error");
                }
            });


            function cancelUpdate() {
                // Show Create button, hide Update button
                document.getElementById("createSchoolBtn").style.display = "inline-block";
                document.getElementById('cancelUpdateBtn').style.display = "none";
                document.getElementById("UpdateSchoolBtn").style.display = "none";

                // Reset form and state
                document.getElementById("schoolName").value = "";
                document.getElementById("schoolDescription").value = "";
                editingSchoolId = null;
            }

        </script>




        </body>

        </html>