
// Logic to switch tabs
document.addEventListener('DOMContentLoaded', function () {
    const tabs = document.querySelectorAll('.tab-link');
    const panels = document.querySelectorAll('.tab-panel');

    // Restore last active tab from localStorage (if any)
    const lastTabId = localStorage.getItem('activeTabId');
    if (lastTabId) {
        const activeTab = document.querySelector(`.tab-link[data-tab="${lastTabId}"]`);
        const activePanel = document.getElementById(lastTabId);
        if (activeTab && activePanel) {
            // Remove existing active states
            tabs.forEach(t => {
                t.classList.remove('active');
                t.setAttribute('aria-selected', 'false');
            });
            panels.forEach(panel => panel.classList.remove('active'));

            // Set saved tab as active
            activeTab.classList.add('active');
            activeTab.setAttribute('aria-selected', 'true');
            activePanel.classList.add('active');
        }
    }

    tabs.forEach(tab => {
        tab.addEventListener('click', () => {
            const target = tab.getAttribute('data-tab');

            // Save clicked tab to localStorage
            localStorage.setItem('activeTabId', target);

            // Remove active from all tabs/panels
            tabs.forEach(t => {
                t.classList.remove('active');
                t.setAttribute('aria-selected', 'false');
            });
            panels.forEach(panel => panel.classList.remove('active'));

            // Activate clicked tab/panel
            tab.classList.add('active');
            tab.setAttribute('aria-selected', 'true');
            document.getElementById(target).classList.add('active');
        });
    });
});

// modal popup open buttons logic
document.addEventListener("DOMContentLoaded", () => {
    document.querySelectorAll(".open-modal-btn").forEach(btn => {
        btn.addEventListener("click", () => {
            const modalType = btn.getAttribute("data-modal");
            const mode = btn.getAttribute("data-mode") || "add";
            const id = btn.getAttribute("data-id") || null;
            openModal(modalType, mode, id);
        });
    });
});


// modalTypes = [hod, rm, executive, department, sub-department]
// corresponding tablebodies = [tablebody-hod, tablebody-rm, tablebody-executive, tablebody-department, tablebody-sub-department]

// open modal popups
function openModal(modalType, mode, id = null) {
    const modalId = `modal-${modalType}`;
    const modal = document.getElementById(modalId);
    const form = modal.querySelector("form.profile-container");
    const title = modal.querySelector(".modal-title");
    const submitBtn = modal.querySelector(".save-profile-btn");
    const inputs = modal.querySelectorAll("input, select, textarea");
    // Reset form
    form.reset();
    if (mode === "add") {
        inputs.forEach(input => input.disabled = false);
    } else {
        inputs.forEach(input => {
            if (input.classList.contains('editable')) {
                input.disabled = false;
            }
        });
    }
    submitBtn.style.display = 'inline-block';

    form.dataset.mode = mode;
    form.dataset.modalType = modalType;
    if (id) form.dataset.id = id; else delete form.dataset.id;


    // Set title and button text
    if (mode === "add") {
        title.textContent = `Add ${capitalize(modalType)}`;
        submitBtn.textContent = "Add";
    } else if (mode === "edit") {
        title.textContent = `Edit ${capitalize(modalType)}`;
        submitBtn.textContent = "Update";
    } else if (mode === "view") {
        title.textContent = `View ${capitalize(modalType)}`;
        submitBtn.textContent = "Update";
        // submitBtn.type = "button";
        submitBtn.style.display = "none";
    }

    // Fetch data if not "add"
    if (mode !== "add" && id) {
        let apiUrl = "";
        let bodyData = "";

        if (modalType === "department") {
            apiUrl = "api/department.php";
            bodyData = `action=get&id=${id}`;
        } else if (modalType === "sub-department") {
            apiUrl = "api/subdepartment.php";
            bodyData = `action=get&id=${id}`;
        } else {
            apiUrl = "api/employee.php";
            bodyData = `action=get&id=${id}`;
        }

        fetch(apiUrl, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded" },
            body: bodyData
        })
            .then(res => res.json())
            .then(data => {
                if (data.status === "success") {
                    const item = data.emp || data.dept || data.subdept;
                    // console.log(item);
                    for (const key in item) {
                        const field = modal.querySelector(`[name="${key}"]`);
                        // console.log(key + ":" + item[key]);
                        // if (field) field.value = item[key];
                        if (field) {
                            field.value = item[key];

                            // Special: trigger change on dept_id to populate dependent selects
                            if (key === 'dept_id') {
                                field.dispatchEvent(new Event('change'));

                                // Delay setting subdept/rm values after options are populated
                                const subdeptId = item['subdept_id'];
                                const rmId = item['rm_id'];

                                setTimeout(() => {
                                    if (subdeptId) {
                                        const subSelect = modal.querySelector('select[name="subdept_id"]');
                                        if (subSelect) subSelect.value = subdeptId;
                                    }

                                    if (rmId) {
                                        const rmSelect = modal.querySelector('select[name="rm_id"]');
                                        if (rmSelect) rmSelect.value = rmId;
                                    }
                                }, 300); // 300ms delay (adjust if needed)
                            }
                        }

                    }

                    if (mode === "view") {
                        inputs.forEach(input => input.disabled = true);
                    }
                } else {
                    alert(data.message || "Data not found");
                }
            })
            .catch(err => {
                console.error("Fetch error:", err);
                alert("Error loading data");
            });
    }

    // Show modal
    modal.classList.add("show");
}

// Helper function
function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

// Toggle Modal Fields editable/disabled
// document.addEventListener("DOMContentLoaded", () => {
//     document.querySelectorAll(".edit-profile-btn").forEach(editBtn => {
//         editBtn.addEventListener("click", () => {
//             const modal = editBtn.closest(".modal");
//             const inputs = modal.querySelectorAll(".editable");
//             const saveBtn = modal.querySelector(".save-profile-btn");
//             // const cancelBtn = modal.querySelector(".cancel-btn");

//             // Toggle edit mode
//             const isDisabled = inputs[0].disabled;
//             inputs.forEach(input => input.disabled = !isDisabled);

//             if (isDisabled) {
//                 saveBtn.style.display = "inline-block";
//             } else {
//                 saveBtn.style.display = "none";
//             }
//         });
//     });

//     // Handle cancel button
//     document.querySelectorAll(".cancel-btn").forEach(cancelBtn => {
//         cancelBtn.addEventListener("click", () => {
//             const modal = cancelBtn.closest(".modal-dialog");
//             modal.classList.remove("show");
//         });
//     });
// });


// Cascade RM dropdown with Dept Dropdown
// document.addEventListener("change", function (e) {
//     if (e.target && e.target.id.includes("dept")) {
//         const deptSelect = e.target;
//         const form = deptSelect.closest(".profile-container");
//         const rmSelect = form.querySelector("select[name='rm_id']");

//         const deptId = deptSelect.value;
//         if (!rmSelect) return;

//         // Reset RM dropdown
//         rmSelect.innerHTML = `<option value="">Select Manager</option>`;

//         if (!deptId) return;

//         fetch('api/employee.php', {
//             method: 'POST',
//             headers: {
//                 'Content-Type': 'application/x-www-form-urlencoded',
//             },
//             body: `action=get_rms_by_dept&dept_id=${deptId}`
//         })
//             .then(res => res.json())
//             .then(data => {
//                 if (data.status === 'success') {
//                     data.rms.forEach(rm => {
//                         const option = document.createElement('option');
//                         option.value = rm.emp_id;
//                         option.textContent = rm.name;
//                         rmSelect.appendChild(option);
//                     });
//                 }
//             })
//             .catch(err => {
//                 console.error("Error fetching RM list:", err);
//             });
//     }
// });


// Handle dept subdept and rm selects
document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('select[name="dept_id"]').forEach(deptSelect => {
        deptSelect.addEventListener('change', async function () {
            const form = this.closest('form');
            const deptId = this.value;

            const subdeptSelect = form.querySelector('select[name="subdept_id"]');
            const rmSelect = form.querySelector('select[name="rm_id"]');

            // Fetch and populate subdepartments if subdept select exists
            if (subdeptSelect) {
                subdeptSelect.innerHTML = `<option value="">Loading...</option>`;
                try {
                    const res = await fetch('api/subdepartment.php', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        body: `action=getByDepartment&id=${deptId}`
                    });
                    const data = await res.json();
                    if (data.status === "success") {
                        subdeptSelect.innerHTML = `<option value="">Select Sub Department</option>`;
                        data.subdepartments.forEach(sub => {
                            const opt = document.createElement('option');
                            opt.value = sub.subdept_id;
                            opt.textContent = sub.subdept_name;
                            subdeptSelect.appendChild(opt);
                        });
                    } else {
                        subdeptSelect.innerHTML = `<option value="">No Sub Departments</option>`;
                    }

                } catch (e) {
                    subdeptSelect.innerHTML = `<option value="">Failed to load</option>`;
                }
            }

            if (rmSelect) {
                const subdeptId = subdeptSelect?.value;
                if (subdeptId) {
                    fetchRMsBySubdept(subdeptId, rmSelect);
                } else {
                    fetchRMsByDept(deptId, rmSelect);
                }
            }

        });
    });

    // For Executive: fetch RM by subdept (or fallback to dept if subdept is not selected)
    document.querySelectorAll('select[name="subdept_id"]').forEach(subdeptSelect => {
        subdeptSelect.addEventListener('change', function () {
            const form = this.closest('form');
            const rmSelect = form.querySelector('select[name="rm_id"]');
            const deptId = form.querySelector('select[name="dept_id"]').value;
            const subdeptId = this.value;

            if (rmSelect) {
                if (subdeptId) {
                    fetchRMsBySubdept(subdeptId, rmSelect);
                } else {
                    fetchRMsByDept(deptId, rmSelect);
                }
            }
        });
    });
});

// Utility: Fetch RMs by Department
async function fetchRMsByDept(deptId, selectEl) {
    selectEl.innerHTML = `<option value="">Loading...</option>`;
    try {
        const res = await fetch('api/employee.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=get-rms&dept_id=${deptId}`
        });
        const data = await res.json();
        if (data.status === "success") {
            selectEl.innerHTML = `<option value="">Select Reporting Manager</option>`;
            data.rms.forEach(rm => {
                const opt = document.createElement('option');
                opt.value = rm.emp_id;
                opt.textContent = rm.name;
                selectEl.appendChild(opt);
            });
        } else {
            selectEl.innerHTML = `<option value="">No Managers</option>`;
        }

    } catch (e) {
        selectEl.innerHTML = `<option value="">Failed to load</option>`;
    }
}

// Utility: Fetch RMs by Subdepartment
async function fetchRMsBySubdept(subdeptId, selectEl) {
    selectEl.innerHTML = `<option value="">Loading...</option>`;
    try {
        const res = await fetch('api/employee.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=get-rms&subdept_id=${subdeptId}`
        });
        const data = await res.json();
        if (data.status === "success") {
            selectEl.innerHTML = `<option value="">Select Reporting Manager</option>`;
            data.rms.forEach(rm => {
                const opt = document.createElement('option');
                opt.value = rm.emp_id;
                opt.textContent = rm.name;
                selectEl.appendChild(opt);
            });
        } else {
            selectEl.innerHTML = `<option value="">No Managers</option>`;

        }

    } catch (e) {
        selectEl.innerHTML = `<option value="">Failed to load</option>`;
    }
}

// Close modal logic
document.querySelectorAll('.close-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        btn.closest('.modal-dialog').classList.remove('show');
    });
});

// Submission Logic with Validations
document.querySelectorAll('.modal-dialog form').forEach(form => {
    form.addEventListener('submit', function (e) {
        e.preventDefault();

        let isValid = true;
        // Validate text inputs
        form.querySelectorAll('input[type="text"]:not([hidden]), input[type="email"]').forEach(input => {
            const errorEl = input.nextElementSibling;
            const value = input.value.trim();

            // console.log('input: ', input);
            // console.log('erEl: ', errorEl);


            if (input.hasAttribute('required') && value === '') {
                errorEl.textContent = 'This field is required';
                errorEl.style.display = 'block';
                isValid = false;
            } else if (input.type === 'email' && !/^[^@]+@[^@]+\.[^@]+$/.test(value)) {
                errorEl.textContent = 'Please enter a valid email';
                errorEl.style.display = 'block';
                isValid = false;
            } else if (input.name === 'emp_id' && !/^[1-9][0-9]{0,3}$/.test(value.trim())) {
                errorEl.textContent = 'Please enter a valid Emp Id (1–9999, no spaces)';
                errorEl.style.display = 'block';
                isValid = false;
            } else if (input.id.endsWith('name') && !/^[A-Za-z\s\-\&]+$/.test(value)) {
                errorEl.textContent = 'Please enter a valid name (alphabets only)';
                errorEl.style.display = 'block';
                isValid = false;
                return
            } else {
                errorEl.style.display = 'none';
            }
        });


        // password + confirm-password validation
        const passwordInput = form.querySelector('input[name="password"]');
        const confirmInput = form.querySelector('input[name="confirm-password"]');

        if (passwordInput && passwordInput.value.trim() !== '') {
            const passErr = passwordInput.closest('.password-wrapper').nextElementSibling;
            if (passwordInput.value.length < 6) {
                passErr.textContent = 'Password must be at least 6 characters';
                passErr.style.display = 'block';
                isValid = false;
            } else {
                passErr.style.display = 'none';
            }

            if (confirmInput) {
                // const confirmErr = confirmInput.nextElementSibling;
                const confirmErr = confirmInput.closest('.password-wrapper').nextElementSibling;
                if (confirmInput.value !== passwordInput.value) {
                    confirmErr.textContent = 'Passwords do not match';
                    confirmErr.style.display = 'block';
                    isValid = false;
                } else {
                    confirmErr.style.display = 'none';
                }
            }
        }

        // Validate selects
        form.querySelectorAll('select').forEach(select => {
            const errorEl = select.nextElementSibling;
            if (select.hasAttribute('required') && !select.value) {
                errorEl.textContent = 'Please select an option';
                errorEl.style.display = 'block';
                isValid = false;
            } else {
                errorEl.style.display = 'none';
            }
        });

        // Submit if valid
        if (isValid) {
            console.log('Form is valid, submit via AJAX or further handling here...');
            // return;
            // yourSubmitHandler(form); // or call save logic

            const mode = form.dataset.mode;
            const modalType = form.dataset.modalType;
            const id = form.dataset.id || '';
            const submitBtn = form.querySelector("button[type='submit']");
            const formData = new FormData(form);
            formData.append("action", mode);
            if (id) formData.append("id", id);

            let apiUrl;
            switch (modalType) {
                case 'department':
                    apiUrl = "api/department.php";
                    break;
                case 'sub-department':
                    apiUrl = "api/subdepartment.php";
                    break;
                default:
                    apiUrl = "api/employee.php";
            }


            // Disable button to prevent repeat submission
            submitBtn.disabled = true;

            fetch(apiUrl, {
                method: "POST",
                body: formData
            })
                .then(res => res.json())
                .then(data => {
                    // alert(data.message);
                    if (data.status === "success") {
                        form.closest(".modal-dialog").classList.remove("show");
                        showToast(data.message);
                        // Optional: Reload table or data view
                        refreshTable(modalType);
                        // setTimeout(() => window.location.reload(), 2000);

                    } else {
                        // form.closest(".modal-dialog").classList.remove("show");
                        showToast(data.message, true);
                    }
                })
                .catch(err => {
                    console.error(err);
                    alert("Submission failed.");
                })
                .finally(() => {
                    submitBtn.disabled = false;
                });

        }
    });

    function refreshTable(modalType) {
        const tableBody = document.getElementById(`tablebody-${modalType}`);
        // console.log(tableBody);
        if (!tableBody) return;

        fetch('api/employee.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'list' })
        })
            // fetch(`api/get-${tableId}.php`) // e.g., get-executive-table.php, get-rm-table.php
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    tableBody.innerHTML = data.data;
                } else {
                    showToast("Failed to load table data", true);
                }
            });
    }


    // Hide error on user input
    form.querySelectorAll('input, select').forEach(el => {
        el.addEventListener('input', () => {
            const errorEl = el.nextElementSibling;
            if (errorEl && errorEl.classList.contains('error')) {
                errorEl.style.display = 'none';
            }
        });
    });
});

// show/hide password toggle
document.addEventListener("DOMContentLoaded", () => {
    document.querySelectorAll(".eye-icon").forEach(icon => {
        icon.addEventListener("click", togglePasswordVisibility);
    });
});

function togglePasswordVisibility(e) {
    const icon = e.currentTarget;
    const passwordInput = icon.closest(".password-wrapper").querySelector("input[type='password'], input[type='text']");
    const eyeIcon = icon.querySelector("i");

    if (!passwordInput) return;

    const isHidden = passwordInput.type === "password";
    passwordInput.type = isHidden ? "text" : "password";

    eyeIcon.classList.toggle("fa-eye-slash", !isHidden);
    eyeIcon.classList.toggle("fa-eye", isHidden);
}


// Form Submission Logic
// document.querySelectorAll(".profile-container").forEach(form => {
//     form.addEventListener("submit", function (e) {
//         e.preventDefault();

//         const mode = form.dataset.mode;
//         const modalType = form.dataset.modalType;
//         const id = form.dataset.id || '';
//         const submitBtn = form.querySelector("button[type='submit']");
//         const formData = new FormData(form);
//         formData.append("action", mode);
//         if (id) formData.append("id", id);

//         let apiUrl;
//         switch (modalType) {
//             case 'department':
//                 apiUrl = "api/department.php";
//                 break;
//             case 'sub-department':
//                 apiUrl = "api/sub-department.php";
//                 break;
//             default:
//                 apiUrl = "api/employee.php";
//         }


//         // Disable button to prevent repeat submission
//         submitBtn.disabled = true;

//         fetch(apiUrl, {
//             method: "POST",
//             body: formData
//         })
//             .then(res => res.json())
//             .then(data => {
//                 // alert(data.message);
//                 if (data.status === "success") {
//                     form.closest(".modal-dialog").classList.remove("show");
//                     showToast(data.message);
//                     // Optional: Reload table or data view
//                     setTimeout(() => window.location.reload(), 3500);

//                 } else {
//                     // form.closest(".modal-dialog").classList.remove("show");
//                     showToast(data.message, true);
//                 }
//             })
//             .catch(err => {
//                 console.error(err);
//                 alert("Submission failed.");
//             })
//             .finally(() => {
//                 submitBtn.disabled = false;
//             });
//     });
// });

// delete employee logic
document.addEventListener('click', (e) => {
    if (e.target.classList.contains('delete-btn-emp')) {
        const empId = e.target.dataset.id;
        const row = e.target.closest('tr');

        showAlert(
            'Are you sure you want to delete this employee?',
            () => {
                fetch('api/employee.php', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'delete', id: empId })
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.status === 'success') {
                            row.remove();
                            showToast(data.message || "Deleted successfully.");
                        } else {
                            showToast(data.message || "Deletion failed.", true);
                        }
                        hideAlert();
                    })
                    .catch(err => {
                        console.error(err);
                        showToast("Something went wrong.", true);
                        hideAlert();
                    });
            },
            () => {
                console.log('Deletion Cancelled');
            },
            "Confirm",
            "Cancel"
        );
    }
});

// delete dept/subdept logic
document.addEventListener('click', (e) => {
    if (e.target.classList.contains('delete-btn-dep')) {
        const id = e.target.dataset.id;
        const type = e.target.dataset.modal; // "department" or "subdepartment"
        const row = e.target.closest('tr');

        const apiUrl = type === 'sub-department'
            ? 'api/subdepartment.php'
            : 'api/department.php';

        const entityName = type === 'sub-department' ? 'subdepartment' : 'department';

        showAlert(
            `Are you sure you want to delete this ${entityName}?`,
            () => {
                fetch(apiUrl, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ action: 'delete', id })
                })
                    .then(res => res.json())
                    .then(data => {
                        if (data.status === 'success') {
                            row.remove();
                            showToast(`${entityName.charAt(0).toUpperCase() + entityName.slice(1)} deleted successfully.`);
                        } else {
                            showToast(data.message || `Failed to delete ${entityName}.`, true);
                        }
                        hideAlert();
                    })
                    .catch(err => {
                        console.error(err);
                        showToast("Something went wrong.", true);
                        hideAlert();
                    });
            },
            () => {
                console.log(`${entityName} deletion cancelled`);
            },
            "Confirm", "Cancel"
        );
    }
});


document.addEventListener('DOMContentLoaded', () => {
    const statusToggles = document.querySelectorAll('.toggle-status');
    statusToggles.forEach(toggle => {
        toggle.addEventListener('change', async function () {
            const empId = this.dataset.id;
            const newStatus = this.checked ? 1 : 0;

            try {
                const response = await fetch('api/employee.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        action: 'toggle_status',
                        emp_id: empId,
                        status: newStatus
                    })
                });
                const result = await response.json();
                if (result.status === 'success') {
                    console.log(`User '${empId}' status updated to ${newStatus == 1 ? 'Active' : 'Inactive'}`);
                    showToast(`User '${empId}' status updated to ${newStatus == 1 ? 'Active' : 'Inactive'}`)
                } else {
                    // alert(`Failed to update status: ${result.message || 'Unknown error'}`);
                    showToast(`Failed to update status: ${result.message || 'Unknown error'}`, true);
                    console.log(`Failed to update status: ${result.message || 'Unknown error'}`);
                    // Rollback UI
                    this.checked = !this.checked;
                }
            } catch (error) {
                console.error('Error:', error);
                // alert('Error updating status. Try again.');
                showToast('Error updating status.', true);
                // Rollback UI
                this.checked = !this.checked;
            }


        });
    });
});


document.addEventListener('DOMContentLoaded', () => {
    document.querySelectorAll('.search-input').forEach(input => {
        input.addEventListener('input', function () {
            const tabPanel = this.closest('.tab-panel');
            const tableBody = tabPanel.querySelector('tbody');
            const rows = Array.from(tableBody.querySelectorAll('tr:not(.no-entries-row)'));
            const noDataRow = tableBody.querySelector('.no-entries-row');
            const query = this.value.trim().toLowerCase();

            let visibleRowsCount = 0;
            rows.forEach(row => {
                const rowText = Array.from(row.cells).map(cell => cell.textContent.toLowerCase()).join(' ');
                if (rowText.includes(query)) {
                    row.style.display = '';
                    visibleRowsCount++;
                } else {
                    row.style.display = 'none';
                }
            });

            if (noDataRow) {
                noDataRow.style.display = visibleRowsCount === 0 ? '' : 'none';
            }
        });
    });

});


