
//================add classes =================
function addClass() {
    let name = document.getElementById("class_name").value.trim();

    // Validate class name
    if (!name) {
        Swal.fire("Error", "Class name is required", "error");
        return;
    }



    // Prepare the data to send to the backend
    const data = {
        class_name: name,

    };

    // Send the data to the backend via a POST request
    fetch("api/add_class_post.php", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
    })
        .then(res => res.json())
        .then(data => {
            if (data.status === "success") {
                Swal.fire("Success", data.message, "success");
                           
                // Reset the form fields
                document.getElementById("class_name").value = "";
                // Reset to default section
                loadClasses();
            } else {
                Swal.fire("Error", data.message, "error");
            }
        })
        .catch(() => {
            Swal.fire("Error", "Server not responding", "error");
        });
}


// =======================LOAD CLASS LIST=========================
// 1. Declare variables at the top
let allClasses = [];
let currentPage = 1;
let rowsPerPage = 5;

// 2. Modern Async Function for Loading Data
async function loadClasses() {
    try {
        const response = await fetch("api/classList.php");
        const data = await response.json();

        if (data.status === "success") {
            allClasses = data.data || []; // Ensure it's an array
            currentPage = 1;
            renderTable();
        } else {
            console.error("API Error:", data.message);
        }
    } catch (error) {
        console.error("Failed to fetch classes:", error);
    }
}

// 3. Helper to prevent "Cannot access before initialization"
function getFilteredData() {
    // Safety check: If allClasses isn't loaded yet, return empty array
    if (!allClasses || !Array.isArray(allClasses)) return [];

    const searchBox = document.getElementById("searchBox");
    const search = searchBox ? searchBox.value.toLowerCase() : "";

    return allClasses.filter(c =>
        c.class_name.toLowerCase().includes(search)
    );
}

// 4. Render function with error handling
function renderTable() {
    const tableBody = document.getElementById("classTable");
    const pageInfo = document.getElementById("pageInfo");

    // Safety check for HTML elements
    if (!tableBody) return;

    let html = "";
    let filtered = getFilteredData();

    // Handle empty data
    if (filtered.length === 0) {
        tableBody.innerHTML = "<tr><td colspan='4' class='text-center'>No classes found</td></tr>";
        if (pageInfo) pageInfo.innerText = "Page 0 of 0";
        return;
    }

    let start = (currentPage - 1) * rowsPerPage;
    let end = start + rowsPerPage;
    let pageData = filtered.slice(start, end);

    pageData.forEach(c => {
        let safeName = c.class_name.replace(/'/g, "\\'");
        let statusBtn = c.status == 1
            ? `<button class="btn btn-sm btn-success text-white" onclick="toggleStatusClass(${c.id}, 0)">Active</button>`
            : `<button class="btn btn-sm btn-secondary text-white" onclick="toggleStatusClass(${c.id}, 1)">Inactive</button>`;

        html += `
            <tr>
                <td>${c.class_name}</td>
                <td>
                    <button class="btn badge text-bg-info" onclick="editClass(${c.id}, '${safeName}')">Edit</button>
                </td>
                <td>
                    <button class="btn badge text-bg-danger" onclick="deleteClass(${c.id})">Delete</button>
                </td>
                <td>${statusBtn}</td>
            </tr>
        `;
    });

    tableBody.innerHTML = html;

    if (pageInfo) {
        pageInfo.innerText = `Page ${currentPage} of ${Math.ceil(filtered.length / rowsPerPage)}`;
    }
}

// Search function
function filterTable() {
    currentPage = 1;
    renderTable();
}

// Pagination functions
function nextPage() {
    let totalPages = Math.ceil(getFilteredData().length / rowsPerPage);
    if (currentPage < totalPages) {
        currentPage++;
        renderTable();
    }
}

function prevPage() {
    if (currentPage > 1) {
        currentPage--;
        renderTable();
    }
}

// 5. Initialize ONLY when DOM is ready to avoid "Element not found" errors
document.addEventListener("DOMContentLoaded", () => {
    loadClasses();
});

// delete class
function deleteClass(id) {
    Swal.fire({
        title: "Are you sure?",
        text: "This class will be deleted",
        icon: "warning",
        showCancelButton: true,
        confirmButtonText: "Yes, delete it"
    }).then((result) => {
        if (result.isConfirmed) {
            fetch("api/class_delete.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ id: id })
            })
                .then(res => res.json())
                .then(data => {
                    if (data.status === "success") {
                        Swal.fire("Deleted", data.message, "success");
                        loadClasses(); // reload list
                    } else {
                        Swal.fire("Error", data.message, "error");
                    }
                });
        }
    });
}
//update class
function editClass(id, currentName) {
    Swal.fire({
        title: "Edit Class",
        html: `
            <div class="form-group">
                <label for="edit_class_name">Class Name:</label>
                <input type="text" class="form-control" id="edit_class_name" value="${currentName}" required>
            </div>
           
            
        `,
        showCancelButton: true,
        confirmButtonText: "Update",
        preConfirm: () => {
            // Get values
            let updatedClassName = document.getElementById("edit_class_name").value.trim();


            // Validate the input
            if (!updatedClassName) {
                Swal.fire("Error", "Class name is required", "error");
                return false;
            }

            // Return values for updating
            return {
                id: id,
                class_name: updatedClassName,

            };
        }
    }).then(result => {
        if (result.isConfirmed) {
            // Send the updated data to the backend
            fetch("api/class_update.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify(result.value) // Pass the updated class data
            })
                .then(res => res.json())
                .then(data => {
                    if (data.status === "success") {
                        Swal.fire("Updated", data.message, "success");
                        loadClasses(); // Refresh the class list after updating
                    } else {
                        Swal.fire("Error", data.message, "error");
                    }
                })
                .catch(() => {
                    Swal.fire("Error", "Server not responding", "error");
                });
        }
    });
}


// toggle class status 
function toggleStatusClass(id, newStatus) {
    let text = newStatus === 1 ? "Activate this class?" : "Deactivate this class?";

    Swal.fire({
        title: text,
        icon: "question",
        showCancelButton: true,
        confirmButtonText: "Yes"
    }).then(result => {
        if (result.isConfirmed) {
            fetch("api/class_status.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    id: id,
                    status: newStatus
                })
            })
                .then(res => res.json())
                .then(data => {
                    if (data.status === "success") {
                        Swal.fire("Success", data.message, "success");
                        loadClasses();
                    } else {
                        Swal.fire("Error", data.message, "error");
                    }
                });
        }
    });
}






// ===============section add ==============
document.addEventListener('DOMContentLoaded', () => {
    // 1. Initial Load: Populate Class Dropdown & Table
    fetchClassesForDropdown();
    loadSectionsTable();

    const sForm = document.getElementById('sectionForm');

    // Safety Check: Only run if form exists on this page
    if (sForm) {
        sForm.addEventListener('submit', async (e) => {
            e.preventDefault();

            const btn = document.getElementById('saveBtn');
            const formData = new FormData(sForm);

            // Start Loading State
            btn.disabled = true;
            btn.innerHTML = `<span class="spinner-border spinner-border-sm"></span> Saving...`;

            try {
                const response = await fetch('api/sections/add_section.php', {
                    method: 'POST',
                    body: formData
                });

                const res = await response.json();

                if (res.status === 'success') {
                    if (res.status === 'success') {
                        // 1. Reset Form
                        sForm.reset();

                        // 2. Refresh Table
                        loadSectionsTable();

                        // 3. Show Professional Toast
                        const toastEl = document.getElementById('successToast');
                        const toast = new bootstrap.Toast(toastEl);
                        toast.show();
                    }
                    sForm.reset();         // Clear the form
                    loadSectionsTable();   // Refresh the list on the right
                } else {
                    alert("Error: " + res.message);
                }
            } catch (err) {
                console.error("Submission failed:", err);
                alert("Critical Error: Could not connect to the server.");
            } finally {
                // Stop Loading State
                btn.disabled = false;
                btn.innerHTML = "Save Section";
            }
        });
    }
});

// Helper: Populate the Dropdown inside the UI
async function fetchClassesForDropdown() {
    const dropdown = document.getElementById('class_dropdown');
    if (!dropdown) return;

    const res = await fetch('api/results/get_classes.php');
    const result = await res.json();

    let html = '<option value="">-- Choose Class --</option>';
    result.data.forEach(c => {
        html += `<option value="${c.id}">${c.class_name}</option>`;
    });
    dropdown.innerHTML = html;
}

// ======================Helper: Load the Table Data=======================
// Global State
// Wrap in a block to fix "Red Line" redeclaration errors
{
    // State Management
    let allSections = [];
    let filteredSections = [];
    let currentPageSections = [];
    let allClasses = [];
    let currentPage = 1;
    const rowsPerPage = 10;

    // --- DATA LOADING ---

    async function loadSectionsTable() {
        const tbody = document.getElementById('sectionTableBody');
        if (!tbody) return;

        try {
            const res = await fetch('api/sections/get_all_sections.php');
            allSections = await res.json();
            applyFilterAndRender();
        } catch (err) {
            console.error("Failed to load sections:", err);
            tbody.innerHTML = `<tr><td colspan="4" class="text-center text-danger">Error loading data.</td></tr>`;
        }
    }

    async function loadClassesList() {
        try {
            const res = await fetch('api/classes/get_classes.php');
            allClasses = await res.json();

            const dropdown = document.getElementById('edit_section_class_id');
            if (dropdown) {
                // Populate dropdown once
                dropdown.innerHTML = '<option value="">Select Class</option>' +
                    allClasses.map(c => `<option value="${c.id}">${c.class_name}</option>`).join('');
            }
        } catch (err) {
            console.error("Failed to load classes:", err);
        }
    }

    // --- UI RENDERING ---

    function applyFilterAndRender() {
        const searchTerm = document.getElementById('tableSearch')?.value.toLowerCase() || "";

        filteredSections = allSections.filter(s =>
            s.class_name.toLowerCase().includes(searchTerm) ||
            s.section_name.toLowerCase().includes(searchTerm)
        );

        const start = (currentPage - 1) * rowsPerPage;
        const end = start + rowsPerPage;
        currentPageSections = filteredSections.slice(start, end);

        renderTableUI();
        renderPaginationControls();
        updatePageInfo(start, end);

        const countBadge = document.getElementById('sectionCount');
        if (countBadge) countBadge.innerText = `${filteredSections.length} Sections`;
    }

    function renderTableUI() {
        const tbody = document.getElementById('sectionTableBody');
        if (!tbody) return;

        if (currentPageSections.length === 0) {
            tbody.innerHTML = `<tr><td colspan="4" class="text-center py-4 text-muted">No results found</td></tr>`;
            return;
        }

        tbody.innerHTML = currentPageSections.map(s => `
            <tr>
                <td class="ps-3 fw-bold text-secondary">${s.class_name}</td>
                <td>${s.section_name}</td>
                <td>
                    <span class="badge ${s.status === 'active' ? 'bg-success' : 'bg-secondary'}">
                        ${s.status.toUpperCase()}
                    </span>
                </td>
                <td class="text-end pe-3">
                    <button class="btn btn-sm btn-outline-primary me-1" onclick="openEditModal(${s.id})">
                        Edit
                    </button>
                    <button class="btn btn-sm btn-outline-danger" onclick="deleteSection(${s.id})">
                        Delete
                    </button>
                </td>
            </tr>
        `).join('');
    }

    function updatePageInfo(start, end) {
        const info = document.getElementById('pageInfoSection');
        if (!info) return;

        const total = filteredSections.length;
        const from = total === 0 ? 0 : start + 1;
        const to = Math.min(end, total);

        info.innerHTML = `Showing <b>${from}</b> to <b>${to}</b> of <b>${total}</b> entries`;
    }

    function renderPaginationControls() {
        const pageCount = Math.ceil(filteredSections.length / rowsPerPage);
        const container = document.getElementById('paginationControls');
        if (!container) return;

        let html = '';
        for (let i = 1; i <= pageCount; i++) {
            html += `<li class="page-item ${i === currentPage ? 'active' : ''}">
                        <button class="page-link shadow-none" onclick="changePage(${i})">${i}</button>
                     </li>`;
        }
        container.innerHTML = html;
    }

    // --- GLOBAL ACTIONS ---

    window.changePage = function (page) {
        currentPage = page;
        applyFilterAndRender();
    };

    window.openEditModal = function (id) {
        // Find the section data
        const section = allSections.find(s => s.id == id);
        // console.log("Section Data:", section);
        if (!section) return;

        // Populate Text Fields
        document.getElementById('edit_id').value = section.id;
        document.getElementById('edit_section_name').value = section.section_name;
        document.getElementById('edit_status').value = section.status;

        // Select the Class in Dropdown
        const classSelect = document.getElementById('edit_section_class_id');
        if (classSelect) {
            // Use String() to ensure the ID matches the option value type
            classSelect.value = String(section.class_id);
        }

        // Show Modal
        const modalEl = document.getElementById('editSectionModal');
        const editModal = bootstrap.Modal.getOrCreateInstance(modalEl);
        editModal.show();
    };

    // --- EVENT LISTENERS ---

    // Submit Edit Form
    document.getElementById('editSectionForm')?.addEventListener('submit', async (e) => {
        e.preventDefault();
        const formData = new FormData(e.target);

        try {
            const res = await fetch('api/sections/update_section.php', {
                method: 'POST',
                body: formData
            });
            const result = await res.json();

            if (result.status === 'success') {
                const modalEl = document.getElementById('editSectionModal');
                const modalInstance = bootstrap.Modal.getInstance(modalEl);
                if (modalInstance) modalInstance.hide();
                // 3. Show Professional Success Msg
                showNotification(result.message, 'success');
                loadSectionsTable(); // Refresh the table UI
            } else {
                alert(result.message || "Update failed");
            }
        } catch (err) {
            console.error("Update failed:", err);
        }
    });

    // Table Search
    document.getElementById('tableSearch')?.addEventListener('input', () => {
        currentPage = 1;
        applyFilterAndRender();
    });

    // Global Refresh
    window.loadSectionsTable = loadSectionsTable;

    // Initial Load
    document.addEventListener('DOMContentLoaded', () => {
        loadClassesList();    // Fetch classes first
        loadSectionsTable();  // Then fetch sections
    });

    // =============succes messgae============= 
    function showNotification(message, type = 'success') {
        const toastEl = document.getElementById('liveToast');
        const toastMsgEl = document.getElementById('toastMessage');

        // Set Color based on type
        toastEl.classList.remove('bg-success', 'bg-danger');
        toastEl.classList.add(`bg-${type}`);

        // Set Message
        toastMsgEl.innerText = message;

        // Initialize and Show Bootstrap Toast
        const toast = new bootstrap.Toast(toastEl, { delay: 3000 });
        toast.show();
    }
    // ====delete section=============
    window.deleteSection = async function (id) {
        if (!confirm("Are you sure?")) return;

        try {
            const res = await fetch(`api/sections/delete_section.php?id=${id}`);
            const result = await res.json();

            if (result.status === 'success') {
                showNotification("Section deleted successfully", "success");
                loadSectionsTable();
            } else {
                showNotification(result.message, "danger");
            }
        } catch (err) {
            showNotification("Delete failed", "danger");
        }
    };
}