document.addEventListener('DOMContentLoaded', () => {
    const start = document.querySelector('input[name="tarikh_mula"]');
    const end = document.querySelector('input[name="tarikh_akhir"]');
    const total = document.getElementById('jumlah_hari');
    const toggle = document.getElementById('theme-toggle');
    const html = document.documentElement;

    function updateDays() {
        if (!start || !end || !total) return;
        const s = new Date(start.value);
        const e = new Date(end.value);
        if (!isNaN(s) && !isNaN(e) && e >= s) {
            const diff = Math.round((e - s) / (1000 * 60 * 60 * 24)) + 1;
            total.value = diff;
        } else {
            total.value = '';
        }
    }

    if (start && end) {
        start.addEventListener('change', updateDays);
        end.addEventListener('change', updateDays);
    }

    if (toggle) {
        toggle.addEventListener('click', () => {
            const current = html.getAttribute('data-bs-theme') === 'dark' ? 'light' : 'dark';
            html.setAttribute('data-bs-theme', current);
            localStorage.setItem('theme', current);
        });
        const stored = localStorage.getItem('theme');
        if (stored) {
            html.setAttribute('data-bs-theme', stored);
        }
    }

    const shell = document.getElementById('appShell');
    const sidebarToggle = document.getElementById('sidebarToggleButton');
    const sidebarToggleButtons = document.querySelectorAll('[data-sidebar-toggle]');
    const sidebarBackdrop = document.getElementById('sidebarBackdrop');
    const sidebarLinks = document.querySelectorAll('.app-sidebar .sidebar-link');

    function closeSidebar() {
        if (!shell) return;
        shell.classList.remove('sidebar-open');
        document.body.classList.remove('sidebar-locked');
        if (sidebarToggle) {
            sidebarToggle.setAttribute('aria-expanded', 'false');
        }
    }

    function openSidebar() {
        if (!shell) return;
        shell.classList.add('sidebar-open');
        document.body.classList.add('sidebar-locked');
        if (sidebarToggle) {
            sidebarToggle.setAttribute('aria-expanded', 'true');
        }
    }

    function toggleSidebar() {
        if (!shell) return;
        if (shell.classList.contains('sidebar-open')) {
            closeSidebar();
        } else {
            openSidebar();
        }
    }

    if (sidebarToggleButtons.length && shell) {
        sidebarToggleButtons.forEach(button => {
            button.addEventListener('click', event => {
                event.preventDefault();
                toggleSidebar();
            });
        });
    }

    if (sidebarBackdrop) {
        sidebarBackdrop.addEventListener('click', closeSidebar);
    }

    sidebarLinks.forEach(link => {
        link.addEventListener('click', () => {
            if (window.innerWidth < 992) {
                closeSidebar();
            }
        });
    });

    window.addEventListener('resize', () => {
        if (window.innerWidth >= 992) {
            closeSidebar();
        }
    });

    document.addEventListener('keyup', event => {
        if (event.key === 'Escape') {
            closeSidebar();
        }
    });

    // Employee edit modal population
    const editEmployeeModal = document.getElementById('editEmployeeModal');
    if (editEmployeeModal) {
        editEmployeeModal.addEventListener('show.bs.modal', event => {
            const button = event.relatedTarget;
            if (!button) return;

            const userId = button.getAttribute('data-user-id');
            const name = button.getAttribute('data-name') || '';
            const email = button.getAttribute('data-email') || '';
            const phone = button.getAttribute('data-phone') || '';
            const location = button.getAttribute('data-location') || '';
            const bank = button.getAttribute('data-bank') || '';
            const account = button.getAttribute('data-account') || '';
            const hireDate = button.getAttribute('data-hire-date') || '';
            const address = button.getAttribute('data-address') || '';
            const allowed = button.getAttribute('data-allowed') || '';

            editEmployeeModal.querySelector('#editEmployeeUserId').value = userId;
            editEmployeeModal.querySelector('#editEmployeeName').value = name;
            editEmployeeModal.querySelector('#editEmployeeEmail').value = email;
            editEmployeeModal.querySelector('#editEmployeePhone').value = phone;
            const locationSelect = editEmployeeModal.querySelector('#editEmployeeLocation');
            if (locationSelect.tagName && locationSelect.tagName.toLowerCase() === 'select') {
                locationSelect.value = location;
            } else {
                locationSelect.value = location;
            }
            editEmployeeModal.querySelector('#editEmployeeBank').value = bank;
            editEmployeeModal.querySelector('#editEmployeeAccount').value = account;
            editEmployeeModal.querySelector('#editEmployeeHireDate').value = hireDate;
            editEmployeeModal.querySelector('#editEmployeeAddress').value = address;
            editEmployeeModal.querySelector('#editEmployeeAllowedLeave').value = allowed;
        });
    }

    const viewEmployeeModal = document.getElementById('viewEmployeeModal');
    if (viewEmployeeModal) {
        viewEmployeeModal.addEventListener('show.bs.modal', event => {
            const button = event.relatedTarget;
            if (!button) return;

            const selector = id => viewEmployeeModal.querySelector(id);
            selector('#viewEmployeeName').textContent = button.getAttribute('data-name') || '-';
            selector('#viewEmployeeLogin').textContent = button.getAttribute('data-login') || '-';
            selector('#viewEmployeeIc').textContent = button.getAttribute('data-ic') || '-';
            selector('#viewEmployeeEmail').textContent = button.getAttribute('data-email') || '-';
            selector('#viewEmployeePhone').textContent = button.getAttribute('data-phone') || '-';
            selector('#viewEmployeeLocation').textContent = button.getAttribute('data-location') || '-';
            selector('#viewEmployeeAddress').textContent = button.getAttribute('data-address') || '-';
            selector('#viewEmployeeBank').textContent = button.getAttribute('data-bank') || '-';
            selector('#viewEmployeeAccount').textContent = button.getAttribute('data-account') || '-';
            selector('#viewEmployeeHireDate').textContent = button.getAttribute('data-hire-date') || '-';
            selector('#viewEmployeeUsedLeave').textContent = (button.getAttribute('data-used') || '0') + ' hari';
            selector('#viewEmployeeAllowedLeave').textContent = (button.getAttribute('data-allowed') || '0') + ' hari';
            selector('#viewEmployeeBalanceLeave').textContent = (button.getAttribute('data-balance') || '0') + ' hari';
        });
    }
});

