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

    <div class="page-wrapper" id="toTop">
        <div class="content">
            <div class="page-header">
                <div class="page-title">
                    <h4>Manage Program Types</h4>
                    <h6>Add/Update/Delete Program Types</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">Program Type</label>
                                <input type="text" id="programTypeName" class="form-control"
                                    placeholder="Enter Program Type">
                            </div>
                        </div>


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

                            <a href="javascript:void(0);" id="UpdateSchoolBtn" class="btn btn-submit me-2">Update
                                Program Type</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 Program Types</h4>

                        </div>
                        <div class="card-body">
                            <div class="table-responsive">
                                <table class="table datanew">
                                    <thead>
                                        <tr>
                                            <th>S/N</th>
                                            <th>Program Type Name</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";
                loadProgramTypes();
            });

            let editingProgramTypeId = null;

            // CREATE
            document.getElementById("createSchoolBtn").addEventListener("click", async function () {
                const programTypeName = document.getElementById("programTypeName").value.trim();
                const token = localStorage.getItem("token");

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

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

                    const data = await res.json();
                    if (!res.ok || !data.success) {
                        throw new Error(data.message || "Failed to create Program Type");
                    }

                    Swal.fire("Success", "Program Type created successfully!", "success");
                    document.getElementById("programTypeName").value = "";
                    loadProgramTypes();

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

            // LOAD
            async function loadProgramTypes() {
                const token = localStorage.getItem("token");

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

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

                    if ($.fn.DataTable.isDataTable('.datanew')) {
                        $('.datanew').DataTable().destroy();
                    }

                    const tbody = document.getElementById("schoolTableBody");
                    tbody.innerHTML = "";

                    programTypes.forEach((type, index) => {
                        const row = document.createElement("tr");
                        row.innerHTML = `
                        <td>${index + 1}</td>
                        <td>${type.programTypeName}</td>
                        <td>
                            <span class="me-2 text-primary action-btns" onclick="editProgramType('${type._id}', '${type.programTypeName}')">
                                <i class="fas fa-pen me-1"></i>Edit
                            </span>
                            <span class="text-danger action-btns" onclick="deleteProgramType('${type._id}')">
                                <i class="fas fa-trash me-1"></i>Delete
                            </span>
                        </td>
                    `;
                        tbody.appendChild(row);
                    });

                    $('.datanew').DataTable();
                } catch (err) {
                    console.error(err);
                    Swal.fire("Error", "Failed to load Program Types", "error");
                }
            }

            // EDIT
            function editProgramType(id, name) {
                document.getElementById("programTypeName").value = name;
                editingProgramTypeId = id;

                document.getElementById("createSchoolBtn").style.display = "none";
                document.getElementById("UpdateSchoolBtn").style.display = "inline-block";
                document.getElementById("cancelUpdateBtn").style.display = "inline-block";

                document.getElementById("programTypeName").scrollIntoView({ behavior: "smooth" });
            }

            // UPDATE
            document.getElementById("UpdateSchoolBtn").addEventListener("click", async function () {
                const programTypeName = document.getElementById("programTypeName").value.trim();
                const token = localStorage.getItem("token");

                if (!editingProgramTypeId) {
                    return Swal.fire("Error", "No Program Type selected", "warning");
                }

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

                try {
                    const res = await fetch(`/api/program-types/${editingProgramTypeId}`, {
                        method: "PUT",
                        headers: {
                            "Content-Type": "application/json",
                            Authorization: `Bearer ${token}`,
                        },
                        body: JSON.stringify({ programTypeName }),
                    });

                    const data = await res.json();
                    if (!res.ok || !data.success) {
                        throw new Error(data.message || "Failed to update Program Type");
                    }

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

                    document.getElementById("programTypeName").value = "";
                    editingProgramTypeId = null;
                    document.getElementById("createSchoolBtn").style.display = "inline-block";
                    document.getElementById("UpdateSchoolBtn").style.display = "none";
                    document.getElementById("cancelUpdateBtn").style.display = "none";

                    loadProgramTypes();

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

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

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

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

            // CANCEL UPDATE
            function cancelUpdate() {
                editingProgramTypeId = null;
                document.getElementById("programTypeName").value = "";

                document.getElementById("createSchoolBtn").style.display = "inline-block";
                document.getElementById("UpdateSchoolBtn").style.display = "none";
                document.getElementById("cancelUpdateBtn").style.display = "none";
            }
        </script>



        </body>

        </html>